httpClient application/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.     }  

 

 

其他参考地址: http://www.iteblog.com/archives/1379

 

 

 

转载于:https://my.oschina.net/ouminzy/blog/719735

在设置application/json之前,需要确定您是在哪个编程语言或框架中使用它。以下是一些常见的编程语言/框架及其设置示例: 在Python中使用Flask框架: ```python from flask import Flask, request app = Flask(__name__) @app.route('/example', methods=['POST']) def example(): data = request.get_json() # 处理json数据 return 'success' if __name__ == '__main__': app.run() ``` 在Java中使用Spring框架: ```java import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class ExampleController { @PostMapping(value = "/example", consumes = MediaType.APPLICATION_JSON_VALUE) public String example(@RequestBody String data) { // 处理json数据 return "success"; } } ``` 在JavaScript中使用Axios库: ```javascript axios.post('/example', { data: { key1: 'value1', key2: 'value2' } }, { headers: { 'Content-Type': 'application/json' } }) .then(response => { console.log(response.data); }) .catch(error => { console.log(error); }); ``` 在C#中使用HttpClient: ```csharp using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; public class Example { public static async Task Main() { using (HttpClient client = new HttpClient()) { var data = new { key1 = "value1", key2 = "value2" }; string json = Newtonsoft.Json.JsonConvert.SerializeObject(data); var content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync("https://example.com/api", content); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } } } ``` 以上示例仅供参考,具体如何设置application/json取决于您所使用的编程语言和框架。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值