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();

猜你喜欢

转载自blog.csdn.net/fangyuandoit/article/details/81000342