httpclient提交json參數的示例詳解
更新時間:2024年02月03日 09:32:25 作者:有一只柴犬
httpclient使用post提交json參數,和使用表單提交區(qū)分,本文結合示例代碼講解的非常詳細,補充介紹了HttpClient請求傳json參數的案例代碼,感興趣的朋友一起看看吧
httpclient提交json參數
httpclient使用post提交json參數,(跟使用表單提交區(qū)分):
private void httpReqUrl(List<HongGuTan> list, String url) throws ClientProtocolException, IOException { logger.info("httpclient執(zhí)行新聞資訊接口開始。"); 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("循環(huán)處理數據列表大小list.size={}", list != null ? list.size() : 0); // 開始循環(huán)組裝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("業(yè)務處理成功!"); } else { logger.error("業(yè)務處理異常"); 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()這個靜態(tài)方法將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()這個靜態(tài)方法將HttpEntity轉換成字符串,防止 // //服務器返回的數據帶有中文,所以在轉換的時候將字符集指定成utf-8就可以了 } return response; } }
到此這篇關于httpclient提交json參數的文章就介紹到這了,更多相關httpclient提交json參數內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring Cloud zuul自定義統(tǒng)一異常處理實現(xiàn)方法
這篇文章主要介紹了Spring Cloud zuul自定義統(tǒng)一異常處理實現(xiàn),需要的朋友可以參考下2018-02-02使用SpringBoot簡單實現(xiàn)一個蘋果支付的場景
這篇文章主要為大家詳細介紹了如何在Spring?Boot項目中集成Apple?Pay功能,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2024-11-11Spring Data JPA的Audit功能審計數據庫的變更
數據庫審計是指當數據庫有記錄變更時,可以記錄數據庫的變更時間和變更人等,這樣以后出問題回溯問責也比較方便,本文討論Spring Data JPA審計數據庫變更問題,感興趣的朋友一起看看吧2021-06-06