当前位置: 代码迷 >> J2SE >> 怎样获得HttpEntity里面的内容解决方案
  详细解决方案

怎样获得HttpEntity里面的内容解决方案

热度:41   发布时间:2016-04-23 20:30:18.0
怎样获得HttpEntity里面的内容
通过HttpPut进行了PUT请求,获得了返回的HttpEntity,并且判断出HttpEntity不为空,但是HttpEntity里面的内容取不出来,代码如下:

HttpResponse httpResponse = httpClient.execute(httpPut);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null){
InputStream instreams = httpEntity.getContent(); 
String str = ConvertStreamToString(instreams);
System.out.println("Response:" + "\n" + str);
}

ConvertStreamToString()函数如下:

// Convert stream to string
    public static String ConvertStreamToString(InputStream is) { 
    
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));      
        StringBuilder sb = new StringBuilder();      
       
        String line = null;      
        try {      
            while ((line = reader.readLine()) != null) {  
                sb.append(line + "\n");      
            }      
        } catch (IOException e) {      
            System.out.println("Error=" + e.toString());      
        } finally {      
            try {      
                is.close();      
            } catch (IOException e) {      
             System.out.println("Error=" + e.toString());      
            }      
        }      
        return sb.toString();  
        
    } 

结果只输出了:
Response:
后面就没有了。输出了Response:,说明httpEntity != null,但是读出的字符串又是空的,这是怎么回事呢?是不是ConvertStreamToString()这个函数有问题,还是httpEntity本来就没东西?
------解决方案--------------------
不知道 你什么原因应该可以的。
这个自带的http
String s= "http://xinjinqiao.tprtc.com/admin/main/pro!lrprolist.do";
 URL url = new URL(s);
 HttpURLConnection http = (HttpURLConnection) url.openConnection();
 http.setDoOutput(true);  
 http.setDoInput(true);  
         http.setRequestMethod("POST");  
 http.connect();  
 OutputStreamWriter out = new OutputStreamWriter(http.getOutputStream(), "UTF-8"); 

 String input = "name=flr&nowpage=1&pagesize=10"; 
 
 out.append(input);  
         out.flush();  
         out.close();  
         int length = (int) http.getContentLength();
         System.out.println(length);
       BufferedReader reader = new BufferedReader(new InputStreamReader(http.getInputStream()));
   String line;
   StringBuffer buffer = new StringBuffer();
   while ((line = reader.readLine()) != null) {
   buffer.append(line);
   }
   reader.close();
   http.disconnect();
   System.out.println(buffer.toString());

------解决方案--------------------
EntityUtils 这个类里面有方法
  相关解决方案