【问题标题】:HttpURLConnection POST-request throws IOExceptionHttpURLConnection POST 请求抛出 IOException
【发布时间】:2014-09-06 20:11:01
【问题描述】:

我正在尝试使用 android HttpUrlConnection 发出 POST 请求。首先,我使用此处的 GET 请求示例:

http://developer.android.com/training/basics/network-ops/connecting.html#http-client

它运行良好(例如我得到 google.com 页面)。然后我进行一些更改以发出 POST 请求:更改 POST 上的请求方法:

conn.setRequestMethod("POST");

并添加此代码(从此处获取:http://developer.android.com/reference/java/net/HttpURLConnection.html):

      conn.setDoOutput(true);
      conn.setChunkedStreamingMode(0);
      OutputStream out = new BufferedOutputStream(conn.getOutputStream());     
      out.close();

所以现在方法 downloadUrl 看起来像这样:

private String downloadUrl(String myurl) throws IOException {
  InputStream is = null;
  // Only display the first 500 characters of the retrieved
  // web page content.
  int len = 500;

  try {
      URL url = new URL(myurl);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(10000 /* milliseconds */);
      conn.setConnectTimeout(15000 /* milliseconds */);

      conn.setDoInput(true);

      conn.setRequestMethod("POST");
      conn.setDoOutput(true);
      conn.setChunkedStreamingMode(0);
      OutputStream out = new BufferedOutputStream(conn.getOutputStream());     
      out.close();

      // Starts the query
      conn.connect();
      int response = conn.getResponseCode();
      Log.d(DEBUG_TAG, "The response is: " + response);
      is = conn.getInputStream();

      // Convert the InputStream into a string
      String contentAsString = readIt(is, len);
      return contentAsString;

  // Makes sure that the InputStream is closed after the app is
  // finished using it.
  } finally {
      if (is != null) {
          is.close();
      } 
  }
}

而且它总是抛出 IOException。你能帮我看看有什么问题吗?

【问题讨论】:

  • 呃...它在哪一行抛出IOException?!
  • 开启is = conn.getInputStream();

标签: java android http-post httpurlconnection


【解决方案1】:

这是因为 Android 不允许您在主 UI 线程上启动网络连接。你必须启动一个后台线程(使用AsyncTask)并从那里开始。

更多详情in this question

【讨论】:

  • 我完全按照developer.android.com/training/basics/network-ops/… 中说明的方式使用 AsyncTask。当我不使用 AsyncTask GET-request 时也会抛出异常(但不是 IOException)。但在我的情况下,GET-request 有效。我很困惑,不知道该怎么办......
【解决方案2】:

我已经解决了这个问题:问题是服务器不接受所选 URL 上的 POST 请求。更改 URL(和服务器)导致请求成功而不会引发异常。

【讨论】: