从Android发送数据到本地网络服务器时Android app强制关闭

时间:2013-11-16 10:41:50

标签: android httpurlconnection


我想将数据发送到本地网络服务器 我使用OutputStreamWriter向网络服务器发出请求

这是我的代码

protected void trySubmit(Editable d1, Editable d2, Editable d3)
{
    HttpURLConnection connection;
    OutputStreamWriter request = null;

    URL url = null;
    String response = null;
    String parameters = "fullname="+d1+"&email="+d2+"&password="+d3;   
    //Toast.makeText(this,"Message from Server: \n"+ parameters, 0).show();

    try
    {
        url = new URL("http://10.0.2.2:8080/labAndroid/submit.php");
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestMethod("POST");    

        request = new OutputStreamWriter(connection.getOutputStream());
        request.write(parameters);
        request.flush();
        request.close();            
        String line = "";               
        InputStreamReader stream_reader = new InputStreamReader(connection.getInputStream());
        BufferedReader reader = new BufferedReader(stream_reader);
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        // Response from server after login process will be stored in response variable.                
        response = sb.toString();
        // You can perform UI operations here
        Toast.makeText(this,"Message from Server: \n"+ response, 0).show();             
        stream_reader.close();
        reader.close();
    }
    catch(IOException e)
    {
        Toast.makeText(this,"Error :?", 0).show(); 
    }

}

但是当我点击这个方法时,我的应用程序关闭了一个力量。 这是我的logcat

11-16 05:36:09.094: E/AndroidRuntime(1461): FATAL EXCEPTION: main
11-16 05:36:09.094: E/AndroidRuntime(1461): Process: com.satryacode.sendtointernet, PID: 1461
11-16 05:36:09.094: E/AndroidRuntime(1461): android.os.NetworkOnMainThreadException
11-16 05:36:09.094: E/AndroidRuntime(1461):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at libcore.io.IoBridge.connect(IoBridge.java:112)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at java.net.Socket.connect(Socket.java:843)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at com.android.okhttp.internal.Platform.connectSocket(Platform.java:131)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at com.android.okhttp.Connection.connect(Connection.java:101)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:294)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at com.satryacode.sendtointernet.MainActivity.trySubmit(MainActivity.java:66)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at com.satryacode.sendtointernet.MainActivity$1.onClick(MainActivity.java:43)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at android.view.View.performClick(View.java:4424)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at android.view.View$PerformClick.run(View.java:18383)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at android.os.Handler.handleCallback(Handler.java:733)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at android.os.Handler.dispatchMessage(Handler.java:95)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at android.os.Looper.loop(Looper.java:137)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at android.app.ActivityThread.main(ActivityThread.java:4998)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at java.lang.reflect.Method.invokeNative(Native Method)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at java.lang.reflect.Method.invoke(Method.java:515)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
11-16 05:36:09.094: E/AndroidRuntime(1461):     at dalvik.system.NativeStart.main(Native Method)

有谁知道如何解决这个问题?谢谢:))

2 个答案:

答案 0 :(得分:1)

this链接上查看我的回答。将您的所有代码放在后台任务中,如下所示

private class async extends AsyncTask<String, String, Boolean>
    {
            Context context;
            ProgressDialog pd;
            boolean flag ;

            async(Context mcontext)
            {
                context = mcontext; 
                pd = new ProgressDialog(activityContext);

            } 

            @Override
            protected void onPreExecute() 
            {
                pd.setTitle("Loading..");
                pd.setMessage("Please Wait...!");
                pd.setCancelable(false);
                pd.show();
                super.onPreExecute();
            }

@Override
protected Boolean doInBackground(String... params) 
{
HttpURLConnection connection;
OutputStreamWriter request = null;

URL url = null;
String response = null;
String parameters = "fullname="+d1+"&email="+d2+"&password="+d3;   
//Toast.makeText(this,"Message from Server: \n"+ parameters, 0).show();

try
{
    url = new URL("http://10.0.2.2:8080/labAndroid/submit.php");
    connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestMethod("POST");    

    request = new OutputStreamWriter(connection.getOutputStream());
    request.write(parameters);
    request.flush();
    request.close();            
    String line = "";               
    InputStreamReader stream_reader = new InputStreamReader(connection.getInputStream());
    BufferedReader reader = new BufferedReader(stream_reader);
    StringBuilder sb = new StringBuilder();
    while ((line = reader.readLine()) != null)
    {
        sb.append(line + "\n");
    }
    // Response from server after login process will be stored in response variable.                
    response = sb.toString();
    // You can perform UI operations here
    Toast.makeText(this,"Message from Server: \n"+ response, 0).show();             
    stream_reader.close();
    reader.close();
    }

            @Override
            protected void onPostExecute(Boolean result) 
            {
                super.onPostExecute(result);

                if(pd.isShowing()) pd.dismiss();
            }
}

答案 1 :(得分:0)

将您的代码从trySubmit(d1, d2, d3)更改为

        new AsyncTask() {
        @Override
        protected Object doInBackground(Object[] params) {
            trySubmit(d1, d2, d3);
            return null;
        }
        }.execute();