httpclient中文乱码问题

工作项目有个需求,需要向第三方提供的接口发生http请求,参数是json字符串,要求是UTF-8编码,我在网上找了好多解决办法,都没有解决。问同事,他提醒我看httpclient的API,我没有去看,结果他通过看API找到了问题的解决办法。代码如下:

主要是在创建HttpClient对象时,可以传入一个参数,该参数可以设定编码(默认的是iso8859-1),设定为UTF-8即可。同时需要注意json字符串的编码。代码如下:

 

	//通过http请求获得相应的字符串
	public static String getResponseTextByHttpRequest(String interfaceUrl, JSONObject obj) throws IllegalStateException, IOException {
		
		log.info("准备进行http请求:"+interfaceUrl);
		
		HttpParams httpParams = new BasicHttpParams();
		httpParams.setParameter("charset", "UTF-8");
		//在创建httpclient时就设置好编码
		HttpClient  httpclient = new DefaultHttpClient(httpParams);
		
				
		HttpPost httppost = new HttpPost(interfaceUrl);
		HttpResponse response = null;
		String text = null;//响应的字符串
		
		if(obj != null){
			
			StringEntity reqEntity = new StringEntity(obj.toString(),"UTF-8");
			reqEntity.setContentType("application/json");
			httppost.setEntity(reqEntity);
			
			System.out.println("------reqEntity--------"+obj.toString()+"------------------------");
			log.info("请求"+interfaceUrl+"时的附加参数"+obj.toString());
		}
		
		response = httpclient.execute(httppost);
		
		
		HttpEntity entity = response.getEntity();
		
		System.out.println(response.getStatusLine());
		log.info(response.getStatusLine());
		if (entity != null) {
			System.out.println("Response content length: " + entity.getContentLength());
			log.info("Response content length: " + entity.getContentLength());
		}
		
		text = readInputStreamToText(entity.getContent());
		
		return text;
	}