httpclient提交json參數(shù)的示例詳解
httpclient提交json參數(shù)
httpclient使用post提交json參數(shù),(跟使用表單提交區(qū)分):
private void httpReqUrl(List<HongGuTan> list, String url)
throws ClientProtocolException, IOException {
logger.info("httpclient執(zhí)行新聞資訊接口開(kāi)始。");
JSONObject json = new JSONObject();
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
// 設(shè)置代理
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)處理數(shù)據(jù)列表大小list.size={}", list != null ? list.size() : 0);
// 開(kāi)始循環(huán)組裝post請(qǐng)求參數(shù),使用倒序進(jìn)行處理
for (int i = list.size() - 1; i >= 0; i--) {
HongGuTan bean = list.get(i);
if (bean == null) {
continue;
}
// 驗(yàn)證參數(shù)
Object[] objs = { bean.getTitle(), bean.getContent(),
bean.getSourceUrl(), bean.getSourceFrom(),
bean.getImgUrls() };
if (!validateData(objs)) {
logger.info("參數(shù)驗(yàn)證有誤。");
continue;
}
// 接收參數(shù)json列表
JSONObject jsonParam = new JSONObject();
jsonParam.put("chnl_id", "11");// 紅谷灘新聞資訊,channelId 77
jsonParam.put("title", bean.getTitle());// 標(biāo)題
jsonParam.put("content", bean.getContent());// 資訊內(nèi)容
jsonParam.put("source_url", bean.getSourceUrl());// 資訊源地址
jsonParam.put("source_name", bean.getSourceFrom());// 來(lái)源網(wǎng)站名稱(chēng)
jsonParam.put("img_urls", bean.getImgUrls());// 采用 url,url,url 的格式進(jìn)行圖片的返回
StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解決中文亂碼問(wèn)題
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()));// 標(biāo)題
//pairList.add(new BasicNameValuePair("content", bean.getContent()));// 資訊內(nèi)容
//pairList.add(new BasicNameValuePair("source_url", bean.getSourceUrl()));// 資訊源地址
//pairList.add(new BasicNameValuePair("source_name", bean.getSourceFrom()));// 來(lái)源網(wǎng)站名稱(chēng)
//pairList.add(new BasicNameValuePair("img_urls", bean.getImgUrls()));// 采用 url,url,url 的格式進(jìn)行圖片的返回
//method.setEntity(new UrlEncodedFormEntity(pairList, "utf-8"));
HttpResponse result = httpClient.execute(method);
// 請(qǐng)求結(jié)束,返回結(jié)果
String resData = EntityUtils.toString(result.getEntity());
JSONObject resJson = json.parseObject(resData);
String code = resJson.get("result_code").toString(); // 對(duì)方接口請(qǐng)求返回結(jié)果:0成功 1失敗
logger.info("請(qǐng)求返回結(jié)果集{'code':" + code + ",'desc':'" + resJson.get("result_desc").toString() + "'}");
if (!StringUtils.isBlank(code) && code.trim().equals("0")) {// 成功
logger.info("業(yè)務(wù)處理成功!");
} else {
logger.error("業(yè)務(wù)處理異常");
Constants.dateMap.put("lastMaxId", bean.getId());
break;
}
}
}
}補(bǔ)充:
HttpClient請(qǐng)求傳json參數(shù)
http請(qǐng)求,參數(shù)為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工具類(lèi)
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) {
// 請(qǐng)求和響應(yīng)都成功了
HttpEntity entity = httpResponse.getEntity();// 調(diào)用getEntity()方法獲取到一個(gè)HttpEntity實(shí)例
response = EntityUtils.toString(entity, "utf-8");// 用EntityUtils.toString()這個(gè)靜態(tài)方法將HttpEntity轉(zhuǎn)換成字符串,防止
// //服務(wù)器返回的數(shù)據(jù)帶有中文,所以在轉(zhuǎn)換的時(shí)候?qū)⒆址付ǔ蓇tf-8就可以了
}
return response;
}
/**
* localhost:8091/message
* @param url http:localhost:8080
* @param method 方法
* @return params 參數(shù)
* @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) {
// 請(qǐng)求和響應(yīng)都成功了
HttpEntity entity = httpResponse.getEntity();// 調(diào)用getEntity()方法獲取到一個(gè)HttpEntity實(shí)例
response = EntityUtils.toString(entity, "utf-8");// 用EntityUtils.toString()這個(gè)靜態(tài)方法將HttpEntity轉(zhuǎn)換成字符串,防止
// //服務(wù)器返回的數(shù)據(jù)帶有中文,所以在轉(zhuǎn)換的時(shí)候?qū)⒆址付ǔ蓇tf-8就可以了
}
return response;
}
}到此這篇關(guān)于httpclient提交json參數(shù)的文章就介紹到這了,更多相關(guān)httpclient提交json參數(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java使用Thumbnailator庫(kù)實(shí)現(xiàn)圖片處理與壓縮功能
Thumbnailator是高性能Java圖像處理庫(kù),支持縮放、旋轉(zhuǎn)、水印添加、裁剪及格式轉(zhuǎn)換,提供易用API和性能優(yōu)化,適合Web應(yīng)用中的圖片處理需求,本文給大家介紹Java使用Thumbnailator庫(kù)實(shí)現(xiàn)圖片處理與壓縮功能,感興趣的朋友一起看看吧2025-08-08
如何在Spring?Boot微服務(wù)使用ValueOperations操作Redis集群String字符串
這篇文章主要介紹了在Spring?Boot微服務(wù)使用ValueOperations操作Redis集群String字符串類(lèi)型數(shù)據(jù),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-06-06
Spring?Security+JWT簡(jiǎn)述(附源碼)
SpringSecurity是一個(gè)強(qiáng)大的可高度定制的認(rèn)證和授權(quán)框架,對(duì)于Spring應(yīng)用來(lái)說(shuō)它是一套Web安全標(biāo)準(zhǔn),下面這篇文章主要給大家介紹了關(guān)于Spring?Security+JWT簡(jiǎn)述的相關(guān)資料,需要的朋友可以參考下2023-04-04
舉例解析Java多線程編程中需要注意的一些關(guān)鍵點(diǎn)
這篇文章主要介紹了Java多線程編程中需要注意的一些關(guān)鍵點(diǎn),包括ThreadLocal變量與原子更新等一些深層次的內(nèi)容,需要的朋友可以參考下2015-11-11
關(guān)于@RequestParam和@RequestBody的用法及說(shuō)明
本文主要介紹了Spring框架中參數(shù)綁定相關(guān)的三個(gè)注解:@RequestParam、@ModelAttribute和@RequestBody的使用場(chǎng)景和區(qū)別,通過(guò)比較它們的使用場(chǎng)景和注意事項(xiàng),幫助讀者快速理解并正確使用這些注解,避免在項(xiàng)目開(kāi)發(fā)中出現(xiàn)常見(jiàn)問(wèn)題2026-03-03
SpringBoot使用WebSocket實(shí)現(xiàn)向前端推送消息功能
WebSocket協(xié)議是基于TCP的一種新的網(wǎng)絡(luò)協(xié)議,它實(shí)現(xiàn)了瀏覽器與服務(wù)器全雙工(full-duplex)通信——允許服務(wù)器主動(dòng)發(fā)送信息給客戶(hù)端,本文給大家介紹了SpringBoot使用WebSocket實(shí)現(xiàn)向前端推送消息功能,需要的朋友可以參考下2024-05-05

