1. 程式人生 > 程式設計 >java 利用HttpClient PostMethod提交json資料操作

java 利用HttpClient PostMethod提交json資料操作

故事前要

今天,在做公司的一個專案,需要和第三方公司進行對接,需要將我們採集到的資料傳送給第三方公司,按照對方提供的文件,傳遞好引數後,httpclient.execute(method)請求後,得到的狀態碼 ,一直是502,猶豫第一次使用HttpClient post json資料,一直懷疑是自己的程式碼問題,最後不知在哪個技術論壇看到 ,有人問url請求中有空格怎麼辦,突然發現對方提供的pdf文件中 竟然包含空格,而我天真的無視掉了 以為是文件的問題。

算了…… 不多BB了….

PostMethod請求注意兩點:

1、如果使用的是公司的伺服器,設定好代理和埠。

2、如果url中有空格,需要使用%20 進行轉義。

貼一下我的程式碼 ,給不會還沒用過不會PostMethod請求的萌新們…

HttpClient httpClient = new HttpClient();
 String host = (String) BaseConfig.get("host");
 String port = (String) BaseConfig.get("port");
 httpClient.getHostConfiguration().setProxy(host,Integer.valueOf(port));
 PostMethod postMethod = new PostMethod(applyurl);
 JSONObject jsonObject = new JSONObject();
 jsonObject.put("name",user.getName());
 jsonObject.put("phone",user.getPhone());
 jsonObject.put("provinceCode",user.getProvinceCode()); 
 jsonObject.put("cityCode",user.getCityCode()); 
 jsonObject.put("buyModelCode",user.getBuyModelCode()); 
 jsonObject.put("dealerCode",user.getDealerCode()); 
 jsonObject.put("url","http:xxx"); 
 String toJson = jsonObject.toString();
 RequestEntity se = new StringRequestEntity (toJson,"application/json","UTF-8");
 postMethod.setRequestEntity(se);
 postMethod.setRequestHeader("Content-Type","application/json");
 //預設的重試策略
 postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
 postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,5000);//設定超時時間
 int httpStatus = hc.executeMethod(postMethod);
 String str=postMethod.getResponseBodyAsString();
 T.console("str-------:"+str);

程式碼很簡單,就不過多解釋了,最後感謝這個坑爹的文件,又讓我學到了一招。

補充:利用HttpClient&PostMethod上傳檔案和請求引數

我就廢話不多說了,大家還是直接看程式碼吧~

//HttpClient發起請求
public static String sendUrlFile(String url,String jsonstr) { 
 String result = "";
 try { 
 HttpClient httpclient = new HttpClient();
 PostMethod post = new PostMethod(url); 
 FilePart filePart = new FilePart("file",new File("/root/桌面/文件/記錄.txt"));
 filePart.setCharSet("utf-8"); 
 post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");
 //Part陣列裝需要傳第的引數和檔案等
 Part[] parts = {new StringPart("username",jsonstr,"utf-8"),filePart};
 MultipartRequestEntity entity = new MultipartRequestEntity(parts,post.getParams());
 post.setRequestEntity(entity);
 int code = httpclient.executeMethod(post);
 //拿到響應結果
 result = new String(post.getResponseBody(),"UTF-8");
 //可釋放連線
 post.releaseConnection(); 
 return result;
 } catch (HttpException h) {
 LOGGER.error("cause HttpException:" + h.getMessage()); 
 } catch (Exception i) {
 LOGGER.error("傳送請求錯誤: url cause IOException:" + i.getMessage());
 } 
 return "";
}
//接收請求伺服器端 引數需要和傳送端一致
@ResponseBody
@RequestMapping(value = “/login”)
public JsonResult revice(@RequestParam(“file”) MultipartFile file,@RequestParam(“username”)String username) throws IOException{
InputStream in = file.getInputStream();
OutputStream out = new FileOutputStream("/root/桌面/ok.txt");
byte[] bs = new byte[1024];
int len;
while(-1 != (len = (in.read(bs)))){
out.write(bs);
}
JsonResult json = new JsonResult();
System.out.println();
json.setResult(“ok”);
return json;
}

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。如有錯誤或未考慮完全的地方,望不吝賜教。