How do I use the command: HttpEntity?

╄→гoц情女王★ 提交于 2019-12-02 09:31:26

If you want the content from the HttpEntity the correct way does not include calling HttpEntity#getContent() to retrieve a stream and doing tons of pointless stuff already available in the Android SDK.

Try this instead.

// Execute the GET call and obtain the response
HttpResponse getResponse = client.execute(get);
HttpEntity responseEntity = getResponse.getEntity();

// Retrieve a String from the response entity
String content = EntityUtils.toString(responseEntity);

// Now content will contain whatever the server responded with and you
// can pass it to your WebView using #loadDataWithBaseURL

Consider using WebView#loadDataWithBaseURL when displaying content - it behaves a lot nicer.

You need to call responseEntity.getContent() to get response in InputStream against your requested URL. Use that stream in your way to present data as you want. For example, if the expected data is String, so you may simply convert this stream into string with the following method:

/**
 * Converts InputStream to String and closes the stream afterwards
 * @param is Stream which needs to be converted to string
 * @return String value out form stream or NULL if stream is null or invalid.
 * Finally the stream is closed too. 
 */
public static String streamToString(InputStream is) {
    try {
        StringBuilder sb = new StringBuilder();
        BufferedReader tmp = new BufferedReader(new InputStreamReader(is),65728);
        String line = null;

        while ((line = tmp.readLine()) != null) {
            sb.append(line);
        }

        //close stream
        is.close();

        return sb.toString();
    }
    catch (IOException e) { e.printStackTrace(); }
    catch (Exception e) { e.printStackTrace(); }

    return null;
}
InputStream is = responseEntity.getContent();
 try{
 BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
         sb.append(reader.readLine() + "\n");
         String line="0";
         while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
          }

     String   result=sb.toString();
          is.close();
 }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
          }

you will have all the content in the String "result"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!