在 Java Android App 中将输入流转换为字符串值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25983425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:05:40  来源:igfitidea点击:

Convert an inputstream to a string value in Java Android App

javaandroid

提问by bobhope

I'm having trouble with function(s) I'm writing. I'm trying to convert an inputstream to a string value. I've written two functions and I'm attempting to extract the String value but my Log.e response is returning NULL. Below is my syntax. What am I doing wrong? Thanks

我在编写函数时遇到问题。我正在尝试将输入流转换为字符串值。我写了两个函数,我试图提取字符串值,但我的 Log.e 响应返回 NULL。下面是我的语法。我究竟做错了什么?谢谢

public JSONArray GetCityDetails(String StateID) {

    @SuppressWarnings("deprecation")
    String url = "http://mywebsite.com/getCity.php?StateID="+URLEncoder.encode(StateID);

    HttpEntity httpEntity = null;

    try{

         DefaultHttpClient httpClient = new DefaultHttpClient();
         HttpGet httpGet = new HttpGet(url);

         HttpResponse httpResponse = httpClient.execute(httpGet);

         httpEntity = httpResponse.getEntity();


    } catch(ClientProtocolException e){
        e.printStackTrace();

    } catch(IOException e){
        e.printStackTrace();
    }


    JSONArray jsonArray = null;
    if(httpEntity !=null){
        try{

            InputStream entityResponse = httpEntity.getContent();
            // not working
            String entityResponseAfterFunctionCall2 = readFully(entityResponse);
            // not working
            String entityResponseAfterFunctionCall3 = letsDoThisAgain(entityResponse);
            Log.e("Entity Response Dude: ", entityResponseAfterFunctionCall3);

            jsonArray = new JSONArray(entityResponseAfterFunctionCall3);

        } catch(JSONException e){
            e.printStackTrace();
        } catch(IOException e){
            e.printStackTrace();
        }
    }

    return jsonArray;
}

public String readFully(InputStream entityResponse) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length = 0;
    while ((length = entityResponse.read(buffer)) != -1) {
        baos.write(buffer, 0, length);
    }
    return baos.toString();
}

public String letsDoThisAgain(InputStream entityResponse){

    InputStreamReader is = new InputStreamReader(entityResponse);
    StringBuilder sb = new StringBuilder();
    BufferedReader br = new BufferedReader(is);
    try {
        String read = br.readLine();

        while(read !=null){
            sb.append(read);
            read = br.readLine();
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    return sb.toString();   
}

}

回答by user3109745

if(inputStream != null)
        {
            BufferedReader br = null;
            StringBuilder sb = new StringBuilder();

            String line;
            try {

                br = new BufferedReader(new InputStreamReader(inputStream));
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            return sb.toString();
        }
        else
        {
            return "";
        }

回答by Alexander Pogrebnyak

Your readFullycall will use your system's default character encoding to transform byte buffer into String. This is NOTwhat you want to happen.

您的readFully调用将使用您系统的默认字符编码将字节缓冲区转换为字符串。这不是您想要发生的事情。

You should use explicit character set in toStringcall. The encoding is usually specified in the HTTP request header.

您应该在toString调用中使用显式字符集。编码通常在 HTTP 请求头中指定。

Here is an example of how to convert a UTF-8encoded string

这是如何转换UTF-8编码字符串的示例

return baos.toString( "UTF-8" );

Your second problem, is once you've consumed the InputString in readFullycall, the letsDoThisAgainwill not have anything to read, because the InputStream will be at the EOF.

您的第二个问题是,一旦您在readFully调用中使用了 InputString ,letsDoThisAgain就不会读取任何内容,因为 InputStream 将位于 EOF。