始终为null输入流

时间:2017-06-27 22:54:44

标签: android httpurlconnection

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

@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;


    }

1 个答案:

答案 0 :(得分:-1)

您可以使用一些服务器请求的库,例如retrofitloopj。我觉得你的要求有些不对劲。或者您可以使用此方法将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;

}