如果没有读取响应,HttpUrlConnection请求将无法工作

时间:2015-11-06 02:58:13

标签: android json httpurlconnection

我试图通过json发布HttpUrlConnection请求(请注意,我只需将数据推送到服务器,响应将被忽略)。我已经完成了一些示例,但仍然无法使其工作,没有数据添加到服务器。

这是我的代码:

   URL url = new URL(urlString);
   connection = (HttpURLConnection) url.openConnection();
   connection.setRequestMethod("POST");
   connection.setDoOutput(true);
   connection.setRequestProperty("Content-Type", "application/json");
   connection.setRequestProperty("Accept", "application/json");

   OutputStream stream = connection.getOutputStream();
   stream.write(requestJSON.toString().getBytes());
   stream.flush();
   stream.close();

更新

我注意到当我尝试在stream.close()之后读取响应时代码有效,例如:

connection.getResponseMessage()

这是否意味着必须阅读回复才能完成请求?

1 个答案:

答案 0 :(得分:1)

使用此

如果请求是GET

findAll(Specification)

//如果请求已发布

 public static String getDataUsingGetRequest(String urlVal) {
    String Content = null;
    BufferedReader reader = null;
    try {
        URL url = new URL(urlVal);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setConnectTimeout(15 * 1000);
        reader = new BufferedReader(new InputStreamReader(
                conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

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

        Content = sb.toString();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            reader.close();
        } catch (Exception ex) {
        }
    }
    return Content;
}