1. 程式人生 > >httpclient4 post 以json方式傳引數

httpclient4 post 以json方式傳引數

public static String sendSetHeaderGetRequestByPostForJson(String url,Map<String,String> map,Map<String,Object> psotMap/*String appUid,String listMsgIds*/ ) throws Exception{
		BufferedReader buffer=null;
		String result="";
		try {
		      CloseableHttpClient httpclient = HttpClients.createDefault();
	              RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();//設定請求和傳輸超時時間
		      HttpPost httpPost = new HttpPost(url);
		      httpPost.setConfig(requestConfig);
                      httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
		      httpPost.addHeader(HTTP.CONTENT_TYPE,  "text/json");
		      httpPost.setHeader("appKey", map.get("appKey"));
		      httpPost.setHeader("nonce", map.get("nonce"));
		      httpPost.setHeader("timestamp", map.get("timestamp"));
		      httpPost.setHeader("signature", map.get("signature"));
		      JSONObject obj=JSONObject.fromObject(psotMap);
		       StringEntity se = new StringEntity(obj.toString());
		       se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
		       httpPost.setEntity(se);
		       CloseableHttpResponse  response= httpclient.execute(httpPost);
		       buffer=new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"utf-8"));
		       result =buffer.readLine();
		       return result;
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			buffer.close();
		}
	    return null;
	  }