httpclient使用post提交json参数



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

 

 
  1. private void httpReqUrl(List<HongGuTan> list, String url)  
  2.             throws ClientProtocolException, IOException {  
  3.   
  4.         logger.info("httpclient执行新闻资讯接口开始。");  
  5.         JSONObject json = new JSONObject();  
  6.         DefaultHttpClient httpClient = new DefaultHttpClient();  
  7.   
  8.         HttpPost method = new HttpPost(url);  
  9.   
  10.         // 设置代理  
  11.         if (IS_NEED_PROXY.equals("1")) {  
  12.             HttpHost proxy = new HttpHost("192.168.13.19", 7777);  
  13.             httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);  
  14.         }  
  15.   
  16.         if (list != null && list.size() > 0) {  
  17.             logger.info("循环处理数据列表大小list.size={}", list != null ? list.size() : 0);  
  18.   
  19.             // 开始循环组装post请求参数,使用倒序进行处理  
  20.             for (int i = list.size() - 1; i >= 0; i--) {  
  21.                 HongGuTan bean = list.get(i);  
  22.                 if (bean == null) {  
  23.                     continue;  
  24.                 }  
  25.                 // 验证参数  
  26.                 Object[] objs = { bean.getTitle(), bean.getContent(),  
  27.                         bean.getSourceUrl(), bean.getSourceFrom(),  
  28.                         bean.getImgUrls() };  
  29.                 if (!validateData(objs)) {  
  30.                     logger.info("参数验证有误。");  
  31.                     continue;  
  32.                 }  
  33.                 // 接收参数json列表  
  34.                 JSONObject jsonParam = new JSONObject();  
  35.                 jsonParam.put("chnl_id", "11");// 红谷滩新闻资讯,channelId 77  
  36.                 jsonParam.put("title", bean.getTitle());// 标题  
  37.                 jsonParam.put("content", bean.getContent());// 资讯内容  
  38.                 jsonParam.put("source_url", bean.getSourceUrl());// 资讯源地址  
  39.                 jsonParam.put("source_name", bean.getSourceFrom());// 来源网站名称  
  40.                 jsonParam.put("img_urls", bean.getImgUrls());// 采用 url,url,url 的格式进行图片的返回  
  41.                   
  42.                 StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题    
  43.                 entity.setContentEncoding("UTF-8");    
  44.                 entity.setContentType("application/json");    
  45.                 method.setEntity(entity);    
  46.                   
  47.                 //这边使用适用正常的表单提交   
  48.   
  49. //               List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();    
  50.                 //pairList.add(new BasicNameValuePair("chnl_id", "11"));   
  51.                 //pairList.add(new BasicNameValuePair("title", bean.getTitle()));// 标题    
  52.                 //pairList.add(new BasicNameValuePair("content", bean.getContent()));// 资讯内容    
  53.                 //pairList.add(new BasicNameValuePair("source_url", bean.getSourceUrl()));// 资讯源地址    
  54.                 //pairList.add(new BasicNameValuePair("source_name", bean.getSourceFrom()));// 来源网站名称    
  55.                 //pairList.add(new BasicNameValuePair("img_urls", bean.getImgUrls()));// 采用 url,url,url 的格式进行图片的返回    
  56.                 //method.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));   
  57.                   
  58.                   
  59.                 HttpResponse result = httpClient.execute(method);  
  60.   
  61.                 // 请求结束,返回结果  
  62.                 String resData = EntityUtils.toString(result.getEntity());  
  63.                 JSONObject resJson = json.parseObject(resData);  
  64.                 String code = resJson.get("result_code").toString(); // 对方接口请求返回结果:0成功  1失败  
  65.                 logger.info("请求返回结果集{'code':" + code + ",'desc':'" + resJson.get("result_desc").toString() + "'}");  
  66.   
  67.                 if (!StringUtils.isBlank(code) && code.trim().equals("0")) {// 成功  
  68.                     logger.info("业务处理成功!");  
  69.                 } else {  
  70.                     logger.error("业务处理异常");  
  71.                     Constants.dateMap.put("lastMaxId", bean.getId());  
  72.                     break;  
  73.                 }  
  74.             }  
  75.         }  
  76.     }  
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;
				}
			}
		}
	}

参考:https://github.com/dwqs/blog/issues/17

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
您也可以使用Apache HttpClient库来模拟发送POST请求,并将JSON数据作为请求体发送。以下是一个示例代码: ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import java.io.BufferedReader; import java.io.InputStreamReader; public class PostJsonRequest { public static void main(String[] args) { try { // 设置请求URL和JSON数据 String url = "http://example.com/api"; String json = "{\"name\": \"John\", \"age\": 30}"; // 创建HttpClient和HttpPost对象 HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); // 将JSON数据作为请求体发送 StringEntity entity = new StringEntity(json); post.setEntity(entity); post.setHeader("Content-type", "application/json"); post.setHeader("Accept", "application/json"); // 发送请求并获取响应 HttpResponse response = client.execute(post); // 打印响应内容 BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { System.out.println(line); } } catch (Exception e) { e.printStackTrace(); } } } ``` 在上述示例中,我们使用了Apache HttpClient库来创建HttpClient和HttpPost对象,并将JSON数据作为请求体发送。注意:在实际使用时,您需要将URL和JSON数据替换为实际的值。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

寅灯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值