如何使用REST Web服务解决POST上的android.os.NetworkOnMainThreadException问题?

时间:2016-12-07 12:07:26

标签: java android json web-services rest

我在测试时是否收到此异常,以确定我的数据是否存储在REST Web服务数据库中。

 W/System.err: android.os.NetworkOnMainThreadException
    W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
    W/System.err:     at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:333)
    W/System.err:     at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
    W/System.err:     at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
    W/System.err:     at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
    W/System.err:     at java.net.Socket.connect(Socket.java:586)
    W/System.err:     at com.android.okhttp.internal.Platform.connectSocket(Platform.java:113)
    W/System.err:     at com.android.okhttp.Connection.connectSocket(Connection.java:196)
    W/System.err:     at com.android.okhttp.Connection.connect(Connection.java:172)
    W/System.err:     at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:367)
    W/System.err:     at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:130)
    W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:329)
    W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
    W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
    W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:126)
    W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:257)
    W/System.err:     at uk.ac.salford.advanceprog.eathere.MainActivity$HttpTask.doInBackground(MainActivity.java:65)
    W/System.err:     at uk.ac.salford.advanceprog.eathere.MainActivity$1.onClick(MainActivity.java:33)
    W/System.err:     at android.view.View.performClick(View.java:5610)
    W/System.err:     at android.view.View$PerformClick.run(View.java:22265)
    W/System.err:     at android.os.Handler.handleCallback(Handler.java:751)
    W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
    W/System.err:     at android.os.Looper.loop(Looper.java:154)
    W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6077)
    W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
    W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
    W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

MainActivity.java

package ...;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

public class MainActivity extends AppCompatActivity {
    Button btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn = (Button) findViewById(R.id.btn1);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HttpTask asnyc = new HttpTask();
                asnyc.doInBackground();
            }
        });


    }

    class HttpTask extends AsyncTask<String, String, String> {
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

        }

        @Override
        protected String doInBackground(String... params) {

            URL url = null;
            try {
                url = new URL("http://127.0.0.1:8080/v1/users");
                HttpURLConnection connection = null;
                JSONObject data = new JSONObject();

                data.put("email", "work@gmail.com");

                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/json");

                if (data != null) {
                    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
                    outputStream.writeBytes(data.toString());
                    outputStream.flush();
                    outputStream.close();
                }

                int responseCode = connection.getResponseCode();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } catch(Exception e){
                e.printStackTrace();
            }
            return null;
        }
    }

}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="uk.ac.salford.advanceprog.eathere.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <Button
        android:text="Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="78dp"
        android:id="@+id/btn1" />
</RelativeLayout>

请注意:我在AndroidManifest.xml文件中包含<uses-permission android:name="android.permission.INTERNET"/>

感谢。

1 个答案:

答案 0 :(得分:1)

替换onCLick()方法代码
HttpTask asnyc = new HttpTask();
asnyc.doInBackground();

HttpTask asnyc = new HttpTask();
asnyc.execute();