我是新來的Android的發展,我需要發送一個非常基本的HTTP POST請求到PHP服務器,以及跨越這個方法來:發送POST請求的Android
protected void performRequest(String name, String pn) {
String POST_PARAMS = "name=" + name + "&phone_number=" + pn;
URL obj = null;
HttpURLConnection con = null;
try {
obj = new URL("theURL");
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
// For POST only - BEGIN
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
Log.i(TAG, "POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
Log.i(TAG, response.toString());
} else {
Log.i(TAG, "POST request did not work.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
但是當我運行這個應用程序崩潰,他說:
FATAL EXCEPTION: main
Process: (the app id), PID: 11515
android.os.NetworkOnMainThreadException
雖然我明白,我需要在後臺線程執行這麼多,有沒有比較簡單的辦法做到這一點?
另外,我見過一種使用HttpClient發送post請求的方法,但似乎不推薦使用。它仍然可用嗎?
在此先感謝!
複製後。這裏有很多其他的帖子。您需要在Asynctask而不是UI線程上進行網絡呼叫。請查找它。 – Actiwitty
你會注意到這個問題的答案已經存在超過4年了。 – njzk2