2014-09-06 173 views
0

我试图做一个POST请求使用android HttpUrlConnection。首先,我用的例子为GET请求从这里:HttpURLConnection POST请求抛出IOException

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异常。你能帮我吗,有什么不对?

+0

呃......它在哪一行抛出'IOException' ?!! – 2014-09-06 20:13:04

+0

On'is = conn.getInputStream();' – 2014-09-06 20:17:31

回答

0

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

1

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

更多详细信息in this question

+0

两者都不起作用 - 在同一行上出现相同的IOException。 – 2014-09-06 21:17:48

+0

对不起,是的,我现在已经更正了答案。 – 2014-09-06 21:56:44

+0

我完全按照http://developer.android.com/training/basics/network-ops/connecting.html#http-client中的说明使用AsyncTask。当我不使用AsyncTask时GET请求也抛出异常(但不是IOException)。但在我的情况下GET请求的作品。我很困惑,不知道该怎么办... – 2014-09-07 17:34:49

相关问题