解决httpclient返回中文有部分乱码的情况

转自:http://blog.csdn.net/songylwq/article/details/11808003 

java 简单的HttpClient工具类,解决返回中文有部分乱码的情况


[java]  view plain  copy
 print ?
  1. import java.io.IOException;  
  2. import java.io.InputStream;  
  3.   
  4. import org.apache.http.HttpEntity;  
  5. import org.apache.http.HttpResponse;  
  6. import org.apache.http.client.ClientProtocolException;  
  7. import org.apache.http.client.HttpClient;  
  8. import org.apache.http.client.methods.HttpGet;  
  9. import org.apache.http.impl.client.DefaultHttpClient;  
  10.   
  11. public class HttpClientUtil {  
  12.     public static String sendGet(String url,String data) throws ClientProtocolException, IOException  
  13.     {  
  14.         // 创建HttpClient实例     
  15.         HttpClient httpclient = new DefaultHttpClient();  
  16.         // 创建Get方法实例     
  17.         HttpGet httpgets = new HttpGet(url+data);    
  18.         HttpResponse response = httpclient.execute(httpgets);    
  19.         HttpEntity entity = response.getEntity();    
  20.         if (entity != null) {    
  21.             InputStream instreams = entity.getContent();    
  22.             String str = convertStreamToString(instreams);  
  23.             httpgets.abort();    
  24.             return str;  
  25.         }  
  26.         return null;  
  27.     }  
  28.       
  29.     public static String convertStreamToString(InputStream is) {      
  30.         StringBuilder sb1 = new StringBuilder();      
  31.         byte[] bytes = new byte[4096];    
  32.         int size = 0;    
  33.           
  34.         try {      
  35.             while ((size = is.read(bytes)) > 0) {    
  36.                 String str = new String(bytes, 0, size, "UTF-8");    
  37.                 sb1.append(str);    
  38.             }    
  39.         } catch (IOException e) {      
  40.             e.printStackTrace();      
  41.         } finally {      
  42.             try {      
  43.                 is.close();      
  44.             } catch (IOException e) {      
  45.                e.printStackTrace();      
  46.             }      
  47.         }      
  48.         return sb1.toString();      
  49.     }  
  50. }  


是完整代码。

你可能感兴趣的:(HttpClient)