gpt4 book ai didi

Android: java.net.protocolException 不支持输出

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:58:19 26 4
gpt4 key购买 nike

我以前使用的是 HttpClientBasicNameValuePairs,由于某些原因我不得不转向 HttpUrlConnection

因此,这段代码使用特定参数发出 HttpPost 请求:

public class MConnections {

static String BaseURL = "http://www.xxxxxxxxx.com";
static String charset = "UTF-8";
private static String result;
private static StringBuilder sb;
private static List<String> cookies = new ArrayList<String>();

public static String PostData(String url, String sa[][]) {

HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL(BaseURL + url)
.openConnection();
} catch (MalformedURLException e1) {
} catch (IOException e1) {
}

cookies = connection.getHeaderFields().get("Set-Cookie");
try{
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=" + charset);
}catch (Exception e) {

//Here i get Exception that "java.lang.IllegalStateException: Already connected"
}
OutputStream output = null;
String query = "";
int n = sa.length;
for (int i = 0; i < n; i++) {
try {
query = query + sa[i][0] + "="
+ URLEncoder.encode(sa[i][1], "UTF-8");
} catch (UnsupportedEncodingException e) {
}
}
try {
output = connection.getOutputStream();
output.write(query.getBytes(charset));
} catch (Exception e) {

//Here i get Exception that "android: java.net.protocolException: Does not support output"
} finally {

if (output != null)
try {
output.close();
} catch (IOException e) {
}
}
InputStream response = null;
try {
response = connection.getInputStream();
} catch (IOException e) {

//Here i get Exception that "java.io.IOException: BufferedInputStream is closed"
} finally {

//But i am closing it here
connection.disconnect();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
response, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine());
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append("\n" + line);
}
response.close();
result = sb.toString();
} catch (Exception e) {
}
return result;
}
}

但是我在代码中得到了这样的异常

实际上,我使用 AsyncTask 从我的 Activity 调用了两次 MConnections.PostData()。这可能会导致异常:已连接,但我正在使用connection.disconnect。但为什么我仍然得到那个异常?

我是不是用错了?

谢谢

最佳答案

对于协议(protocol)异常,尝试在调用 getOutputStream() 之前添加以下内容:

connection.setDoOutput(true);

感谢 Brian Roach 在这里的回答,发现了这个答案:https://stackoverflow.com/a/14026377/387781

旁注:我在运行 Gingerbread 的 HTC Thunderbolt 上遇到了这个问题,但在运行 Jelly Bean 的 Nexus 4 上却没有。

关于Android: java.net.protocolException 不支持输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13247836/

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