gpt4 book ai didi

java - Android发送post请求时出错

转载 作者:太空宇宙 更新时间:2023-11-04 14:16:44 25 4
gpt4 key购买 nike

我有这个方法:

public String post(String urlParameters, String url) throws IOException{
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Chrome");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}

它编译得很好,但无法运行。在 list 中,存在互联网许可。它说(在 logcat 中)

12-24 14:59:31.028 E/AndroidRuntime(30941): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fliife.bitvisitorbot/com.fliife.bitvisitorbot.MainActivity}: android.os.NetworkOnMainThreadException

我能做什么?

最佳答案

当应用程序尝试在其主线程上执行网络操作时,会引发此异常,因为网络操作可能会涉及不可预测的延迟。为了防止这种情况导致糟糕的用户体验,请始终在与 UI 不同的线程上执行网络操作。 AsyncTask 类提供了从 UI 线程触发新任务的最简单方法之一。

参见:AsyncTask :

仅供引用,只有针对 Honeycomb SDK 或更高版本的应用程序才会抛出此错误。允许针对早期 SDK 版本的应用程序在其主事件循环线程上进行联网,但强烈建议不要这么做。

关于java - Android发送post请求时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27638311/

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