發送POST請求時,我有這樣的方法:錯誤的Android
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();
}
它編譯罰款,但它不會運行。聯合國清單中存在互聯網許可。 它說(在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
我能做些什麼?