1. 程式人生 > >httpclient 傳送請求,帶中文資訊

httpclient 傳送請求,帶中文資訊

有些功能 通過瀏覽器或者postman來代用沒問題。可是有時候通過java程式碼來呼叫,就容易出現中文亂碼


通過httpclient的get方法傳送中文

String location = "嘻哈";
		CloseableHttpClient httpClient = HttpClients.createDefault();// 建立http例項
		CloseableHttpResponse response = null;
		HttpGet httpGet =new HttpGet("http://127.0.0.1:8080/ServiceLocationSwitch/LocationSwitch/locationToLatAndLngForInternal.html?data="+location+"");
 	    httpGet.setHeader("Content-Type","application/html; charset=UTF-8");
 	   response = httpClient.execute(httpGet);
		HttpEntity entity = response.getEntity(); //請求型別
		String content = EntityUtils.toString(entity, "utf-8");
		System.out.println(content);
        response.close();
		httpClient.close();
		





通過httpclient的post方法傳送中文


String location ="中國";
	
	CloseableHttpClient httpClient = HttpClients.createDefault();// 建立http例項
	HttpPost httpPost =new HttpPost();
      httpPost.setURI(new URI("http://127.0.0.1:8080/ServiceLocationSwitch/LocationSwitch/locationToLatAndLngForInternal.html"));
	
      JSONObject object =new JSONObject();
      object.put("location", location);
      
	List<NameValuePair> parms = new ArrayList<NameValuePair>();
	parms.add(new BasicNameValuePair("data", object.toJSONString()));
	httpPost.setEntity(new UrlEncodedFormEntity(parms,"utf-8"));
	
	CloseableHttpResponse response = httpClient.execute(httpPost);
	HttpEntity entity = response.getEntity(); //請求型別
	String content = EntityUtils.toString(entity, "utf-8");
	System.out.println(content);
	 response.close();
	 httpClient.close();