【问题标题】:Always null inputstream始终为空输入流
【发布时间】:2017-06-27 22:54:43
【问题描述】:

我正在尝试使用脚本来实现登录活动。该脚本正在运行,我已经在邮递员应用程序中测试了该脚本。我以 json 格式发送数据,服务器以 json 格式发送响应。当我尝试阅读响应时,它始终为空。有人可以帮忙吗?

@Override
    protected String doInBackground(String... params) {
        String data="";
        JSONObject jsonobj = new JSONObject();
        JSONObject Data=new JSONObject();
        try {
            Data.put("service","emailsignin");
            Data.put("email_id",mEmail);
            Data.put("password",mPassword);
            Data.put("device_token","ABCD");
            Data.put("device_type","A");
            Data.put("user_type_id","2");
            jsonobj.put("data",Data);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpURLConnection httpURLConnection = null;
        BufferedReader reader=null;
        String write_data=String.valueOf(jsonobj);
        Log.e("write_data:",write_data);
        try {
            httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
            httpURLConnection.setRequestMethod("POST");

            httpURLConnection.setDoInput(true);

            Writer writer = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8"));
          writer.write(write_data);
          writer.close();
          InputStream inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
          reader = new BufferedReader(newInputStreamReader(inputStream));
            StringBuilder buffer = new StringBuilder();

            String inputLine;
            while ((inputLine = reader.readLine()) != null) {
                Log.e("LoginActivity:",inputLine);
                buffer.append(inputLine).append("\n");
            }
            if (buffer.length() == 0) {
                // Stream was empty. No point in parsing.
                Log.e("LoginActivity:","input string empty");
                return null;
            }
            data = buffer.toString();

            Log.e("Response is:",data);
            try {

                return data;
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            return null;


        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e("Log In:", "Error closing stream", e);
                }
            }
        }
        return null;


    }

【问题讨论】:

  • 您可能只需要添加以下属性:httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
  • 准确无误。这里没有“始终为空的输入流”或“响应......始终为空”。有一个 empty 响应,它由 your code translated 为 null。或者可能是您未在此处报告的IOException,之后,您的代码 再次返回 null。一个try/catch 围绕一个仅仅return 声明是完全没有意义的。

标签: android httpurlconnection


【解决方案1】:

您可以使用一些为您执行服务器请求的库,例如 retrofit 或 loopj。我觉得你的要求有问题。或者您可以使用此方法将 json 发布到服务器(您将需要 org.apache.http jar 或通过 gradle 添加它):

public static String POST(String url){
    InputStream inputStream = null;
    String result = "";
    try {

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);

        String json = "";

        // 3. build jsonObject
        JSONObject jsonObject = new JSONObject();
        //your json fields fill here

        // 4. convert JSONObject to JSON to String
        json = jsonObject.toString();

        // ** Alternative way to convert Person object to JSON string usin Jackson Lib
        // ObjectMapper mapper = new ObjectMapper();
        // json = mapper.writeValueAsString(person);

        // 5. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 6. set httpPost Entity
        httpPost.setEntity(se);

        // 7. Set some headers to inform server about the type of the content
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        // 8. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        // 9. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // 10. convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    // 11. return result
    return result;
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException{
    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 2020-11-27
    • 2011-11-10
    • 2019-10-11
    • 1970-01-01
    • 2020-07-09
    • 2016-12-10
    相关资源
    最近更新 更多