Java:读取HTTP POST发送的数据(Android AVD)

时间:2016-12-19 13:24:48

标签: java android http

我使用http://www.java2s.com/Code/Java/Network-Protocol/AverysimpleWebserverWhenitreceivesaHTTPrequestitsendstherequestbackasthereply.htm

中的简单WebServer

和来自Sending json object via http post method in android

的Android代码

在我的主要活动中:

AsyncT asyncT = new AsyncT();
asyncT.execute();

班级:

class AsyncT extends AsyncTask<Void,Void,Void>{

    @Override
    protected Void doInBackground(Void... params) {

        try {
            URL url = new URL(""); //Enter URL here
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST"); // here you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc.
            httpURLConnection.setRequestProperty("Content-Type", "application/json"); // here you are setting the `Content-Type` for the data you are sending which is `application/json`
            httpURLConnection.connect();

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("para_1", "arg_1");

            DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
            wr.writeBytes(jsonObject.toString());
            wr.flush();
            wr.close();

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

        return null;
    }


}

建立连接时没有任何错误(&#34; HostConnection :: get()建立了新的主机连接&#34;)。但是,我无法从我的Java服务器获取请求中的任何信息。当我从输入流

中读取时
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    System.out.println(in); 

我得到了java.io.BufferedReader@4d7hge12

这没有任何结果:

String line;
    while ((line = in.readLine()) != null) {
      if (line.length() == 0)
        break;
      System.out.println(line);
    }

2 个答案:

答案 0 :(得分:0)

不要重新发明轮子并为此使用库。

例如okhttp

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();

    Response response = client.newCall(request).execute();
    return response.body().string();
}

如果您想调用REST-API,可以使用retrofit(构建在okhttp之上)

答案 1 :(得分:0)

假设您将此作为一项学习练习,那么使用其他图书馆并不是您正在寻找的内容,我建议您做几件事:

(1)安装Wireshark并查看服务器返回的实际响应是什么,它看起来是否合理?

(2)将那行代码分成单独的行,是否是InputStream / InputStreamReader为空?