gpt4 book ai didi

java - HttpURLConnection POST 请求抛出 IOException

转载 作者:行者123 更新时间:2023-12-01 12:34:19 25 4
gpt4 key购买 nike

我正在尝试使用 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。你能帮帮我吗,出了什么问题?

最佳答案

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

更多详细信息in this question .

关于java - HttpURLConnection POST 请求抛出 IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25704303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com