HttpURLConnection POST-request抛出IOException

时间:2014-09-06 20:11:02

标签: java android http-post httpurlconnection

我正在尝试使用android HttpUrlConnection 制作 POST-request 。首先,我从这里使用GET-request的示例:

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 。你能帮助我吗,出了什么问题?

2 个答案:

答案 0 :(得分:1)

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

更多细节in this question

答案 1 :(得分:0)

我已经卖掉了这个问题:事情是服务器没有接受所选URL的POST请求。更改URL(和服务器)导致请求成功而不会抛出异常。