httpclient提交json参数的示例详解

 更新时间:2024年02月03日 09:32:25   作者:有一只柴犬  
httpclient使用post提交json参数,和使用表单提交区分,本文结合示例代码讲解的非常详细,补充介绍了HttpClient请求传json参数的案例代码,感兴趣的朋友一起看看吧

httpclient提交json参数

httpclient使用post提交json参数,(跟使用表单提交区分):

private void httpReqUrl(List<HongGuTan> list, String url)
			throws ClientProtocolException, IOException {
		logger.info("httpclient执行新闻资讯接口开始。");
		JSONObject json = new JSONObject();
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost method = new HttpPost(url);
		// 设置代理
		if (IS_NEED_PROXY.equals("1")) {
			HttpHost proxy = new HttpHost("192.168.13.19", 7777);
			httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
		}
		if (list != null && list.size() > 0) {
			logger.info("循环处理数据列表大小list.size={}", list != null ? list.size() : 0);
			// 开始循环组装post请求参数,使用倒序进行处理
			for (int i = list.size() - 1; i >= 0; i--) {
				HongGuTan bean = list.get(i);
				if (bean == null) {
					continue;
				}
				// 验证参数
				Object[] objs = { bean.getTitle(), bean.getContent(),
						bean.getSourceUrl(), bean.getSourceFrom(),
						bean.getImgUrls() };
				if (!validateData(objs)) {
					logger.info("参数验证有误。");
					continue;
				}
				// 接收参数json列表
				JSONObject jsonParam = new JSONObject();
				jsonParam.put("chnl_id", "11");// 红谷滩新闻资讯,channelId 77
				jsonParam.put("title", bean.getTitle());// 标题
				jsonParam.put("content", bean.getContent());// 资讯内容
				jsonParam.put("source_url", bean.getSourceUrl());// 资讯源地址
				jsonParam.put("source_name", bean.getSourceFrom());// 来源网站名称
				jsonParam.put("img_urls", bean.getImgUrls());// 采用 url,url,url 的格式进行图片的返回
				StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题  
				entity.setContentEncoding("UTF-8");  
				entity.setContentType("application/json");  
				method.setEntity(entity);  
				//这边使用适用正常的表单提交 
//				 List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();  
				//pairList.add(new BasicNameValuePair("chnl_id", "11")); 
				//pairList.add(new BasicNameValuePair("title", bean.getTitle()));// 标题  
				//pairList.add(new BasicNameValuePair("content", bean.getContent()));// 资讯内容  
				//pairList.add(new BasicNameValuePair("source_url", bean.getSourceUrl()));// 资讯源地址  
				//pairList.add(new BasicNameValuePair("source_name", bean.getSourceFrom()));// 来源网站名称  
				//pairList.add(new BasicNameValuePair("img_urls", bean.getImgUrls()));// 采用 url,url,url 的格式进行图片的返回  
				//method.setEntity(new UrlEncodedFormEntity(pairList, "utf-8")); 
				HttpResponse result = httpClient.execute(method);
				// 请求结束,返回结果
				String resData = EntityUtils.toString(result.getEntity());
				JSONObject resJson = json.parseObject(resData);
				String code = resJson.get("result_code").toString(); // 对方接口请求返回结果:0成功  1失败
				logger.info("请求返回结果集{'code':" + code + ",'desc':'" + resJson.get("result_desc").toString() + "'}");
				if (!StringUtils.isBlank(code) && code.trim().equals("0")) {// 成功
					logger.info("业务处理成功!");
				} else {
					logger.error("业务处理异常");
					Constants.dateMap.put("lastMaxId", bean.getId());
					break;
				}
			}
		}
	}

补充:

HttpClient请求传json参数

http请求,参数为json字符串

public String setMessage(String requestData) {
		String result = "";
		try {
			result = HttpClientUtils.doPost(url, method, requestData);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			throw new ValidationException(SystemError.CONNECTION_FAIL);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;    }

HttpClientUtils工具类

package com.feeling.mc.agenda.util;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
/**
 * 使用
 * @author liangwenbo
 *
 */
@SuppressWarnings({ "resource", "deprecation" })
public class HttpClientUtils {
	public static String doGet(String url,String params) throws ClientProtocolException, IOException {
		String response = null;
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse httpResponse = httpClient.execute(httpGet);
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			// 请求和响应都成功了
			HttpEntity entity = httpResponse.getEntity();// 调用getEntity()方法获取到一个HttpEntity实例
			response = EntityUtils.toString(entity, "utf-8");// 用EntityUtils.toString()这个静态方法将HttpEntity转换成字符串,防止
																// //服务器返回的数据带有中文,所以在转换的时候将字符集指定成utf-8就可以了
		}
		return response;
	}
	/**
	 * localhost:8091/message
	 * @param url http:localhost:8080
	 * @param method 方法
	 * @return params 参数
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public static String doPost(String url, String method, String params) throws ClientProtocolException, IOException {
		String response = null;
		String sendUrl = url+method;
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(sendUrl);
		 if (StringUtils.isNotBlank(params)) {
			 httpPost.setEntity(new StringEntity(params, "utf-8"));
	     }
		HttpResponse httpResponse = httpClient.execute(httpPost); 
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			// 请求和响应都成功了
			HttpEntity entity = httpResponse.getEntity();// 调用getEntity()方法获取到一个HttpEntity实例
			response = EntityUtils.toString(entity, "utf-8");// 用EntityUtils.toString()这个静态方法将HttpEntity转换成字符串,防止
																// //服务器返回的数据带有中文,所以在转换的时候将字符集指定成utf-8就可以了
		}
		return response;
	}
}

到此这篇关于httpclient提交json参数的文章就介绍到这了,更多相关httpclient提交json参数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Mybatis中的延迟加载详细解读

    Mybatis中的延迟加载详细解读

    这篇文章主要介绍了Mybatis中的延迟加载详细解读,Mybatis中延迟加载又称为懒加载,是指在进行关联查询时,按照设置延迟规则推迟对关联对象的select查询,延迟加载可以有效的减少数据库的压力,需要的朋友可以参考下
    2023-10-10
  • Java使用Thumbnailator库实现图片处理与压缩功能

    Java使用Thumbnailator库实现图片处理与压缩功能

    Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应用中的图片处理需求,本文给大家介绍Java使用Thumbnailator库实现图片处理与压缩功能,感兴趣的朋友一起看看吧
    2025-08-08
  • java时间格式的简单整理

    java时间格式的简单整理

    这篇文章主要介绍了java时间格式的简单整理,文中通过示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考一下
    2019-06-06
  • 如何在Spring Boot微服务使用ValueOperations操作Redis集群String字符串

    如何在Spring Boot微服务使用ValueOperations操作Redis集群String字符串

    这篇文章主要介绍了在Spring Boot微服务使用ValueOperations操作Redis集群String字符串类型数据,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-06-06
  • Spring Security+JWT简述(附源码)

    Spring Security+JWT简述(附源码)

    SpringSecurity是一个强大的可高度定制的认证和授权框架,对于Spring应用来说它是一套Web安全标准,下面这篇文章主要给大家介绍了关于Spring Security+JWT简述的相关资料,需要的朋友可以参考下
    2023-04-04
  • 举例解析Java多线程编程中需要注意的一些关键点

    举例解析Java多线程编程中需要注意的一些关键点

    这篇文章主要介绍了Java多线程编程中需要注意的一些关键点,包括ThreadLocal变量与原子更新等一些深层次的内容,需要的朋友可以参考下
    2015-11-11
  • 关于ireport中传入list的处理方式

    关于ireport中传入list的处理方式

    这篇文章主要介绍了关于ireport中传入list的处理方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-02-02
  • 关于@RequestParam和@RequestBody的用法及说明

    关于@RequestParam和@RequestBody的用法及说明

    本文主要介绍了Spring框架中参数绑定相关的三个注解:@RequestParam、@ModelAttribute和@RequestBody的使用场景和区别,通过比较它们的使用场景和注意事项,帮助读者快速理解并正确使用这些注解,避免在项目开发中出现常见问题
    2026-03-03
  • Springboot异常日志输出方式

    Springboot异常日志输出方式

    这篇文章主要介绍了Springboot异常日志输出方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-12-12
  • SpringBoot使用WebSocket实现向前端推送消息功能

    SpringBoot使用WebSocket实现向前端推送消息功能

    WebSocket协议是基于TCP的一种新的网络协议,它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端,本文给大家介绍了SpringBoot使用WebSocket实现向前端推送消息功能,需要的朋友可以参考下
    2024-05-05

最新评论