我正在尝试在Android中发布帖子请求。这是我正在使用的代码,但它导致应用程序崩溃
String urlParameters = "user="+ email.getText().toString() + "&name="+ Username.getText().toString() + "&pass="+ pass.getText().toString() +"";
// Send post request
URL serverUrl =
new URL("http://schoolcheating.3eeweb.com/new_user.php");
HttpURLConnection urlConnection = (HttpURLConnection) serverUrl.openConnection();
// Indicate that we want to write to the HTTP request body
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
// Writing the post data to the HTTP request body
BufferedWriter httpRequestBodyWriter =
new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream()));
httpRequestBodyWriter.write(urlParameters);
httpRequestBodyWriter.close();
崩溃发生在定义off" httpRequestBodyWriter"。这是错误日志:
10-24 19:48:04.049 10501-10501/com.example.mohamedsherif.mysql E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.mohamedsherif.mysql, PID: 10501
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4221)
at android.view.View.performClick(View.java:5155)
at android.view.View$PerformClick.run(View.java:20747)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4216)
at android.view.View.performClick(View.java:5155)
at android.view.View$PerformClick.run(View.java:20747)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:361)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:289)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:208)
at com.example.mohamedsherif.mysql.MainActivity.llll(MainActivity.java:73)
at com.example.mohamedsherif.mysql.MainActivity.cr(MainActivity.java:57)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4216)
at android.view.View.performClick(View.java:5155)
at android.view.View$PerformClick.run(View.java:20747)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5832)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
这也是我发送给它的文件的php代码
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name'])) {
$user = $_POST['user']; //User Name
$pass = $_POST['pass']; //Password
$name = $_POST['name']; //Name
$school = $_POST['school']; //School
$type = $_POST['type']; //Type
$pic = $_POST['pic']; //Profile Picture
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO user(username, name, school, type, profile_picture, password) VALUES('$user', '$name', '$school', '$type', '$pic', '$pass')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "User successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
答案 0 :(得分:0)
根据您的错误日志,您收到 NetworkOnMainThreadException ,这是因为您正在主线程即UI线程上执行网络操作。您需要在后台线程中执行此操作,例如 AsyncTask 。将您的网络连接代码放在AsyncTask的doInBackground()中。
private class BackgroundOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params)
//Your network connection code should be here .
String response = postCall();
return response ;
}
@Override
protected void onPostExecute(String result) {
//Print your response here .
Log.d("Post Response",result);
}
@Override
protected void onPreExecute() {}
@Override
protected void onProgressUpdate(Void... values) {}
}
public String postCall(){
URL url;
HashMap<String ,String> postDataParams = new HashMap<String ,String>();
postDataParams .put("user", email.getText().toString());
postDataParams .put("name", Username.getText().toString());
postDataParams .put("pass", pass.getText().toString());
String response = "";
try {
url = new URL(""http://schoolcheating.3eeweb.com/new_user.php"");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if(responseCode == HttpsURLConnection.HTTP_OK){
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {response+=line;}}else {
response=""; }
} catch (Exception e) {
e.printStackTrace();}
return response;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
现在,您可以使用以下代码从您的活动的onCreate()函数中调用以上内容。
new BackgroundOperation().execute("");
注意:不要忘记在manifest.xml中提及以下权限
<uses-permission android:name="android.permission.INTERNET" />