我是新来的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