HTTP请求不起作用?

时间:2017-11-11 08:34:03

标签: android androidhttpclient networkonmainthread okhttp

我正在尝试创建一个应用程序,当点击一个按钮并且数据来自表单时,该应用程序会将一些数据发送到Web服务器。数据类型是名字,姓氏等。我是一名初学者,并尝试使用OKHTTPFClient插件从应用程序发送HTTP请求。 我需要的是点击表单数据将被发送到PHP然后PHP将给出成功响应,然后应用程序获取,然后活动将被重定向到感谢您的活动。这是我现在正在尝试的代码 -

submitRequest.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if ( firstName.getText().toString().length() == 0 ) {
                firstName.setError("Please enter your first name!");
            }
            if ( firstName.getText().toString().length() != 0 ) {

                Toast.makeText(getApplicationContext(), firstName.getText().toString(), Toast.LENGTH_SHORT).show();

                requestHTTP(firstName.getText().toString());

            } else {

            }
        }
    });

这是OKHTTPClient的方法 -

private void requestHTTP(String first_name) {
    OkHttpClient httpClient = new OkHttpClient();
    String url = "https://www.example.com/action.php";

    RequestBody formBody = new FormBody.Builder()
            .add("first_name", first_name)
            .build();
    Request request = new Request.Builder()
            .url(url)
            .post(formBody)
            .build();
    Response response = null;
    try {
        response = httpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            Toast.makeText(getApplicationContext(), firstName.getText().toString(), Toast.LENGTH_SHORT).show();
        }

    } catch (IOException e) {

    }
}

更新:

以下是Android Run部分显示的错误 -

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.androidapp, PID: 11592
              android.os.NetworkOnMainThreadException
                  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
                  at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86)
                  at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
                  at java.net.InetAddress.getAllByName(InetAddress.java:752)
                  at okhttp3.Dns$1.lookup(Dns.java:39)
                  at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:185)
                  at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.java:149)
                  at okhttp3.internal.connection.RouteSelector.next(RouteSelector.java:84)
                  at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:213)
                  at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:134)
                  at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:113)
                  at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
                  at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
                  at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
                  at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
                  at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
                  at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
                  at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
                  at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
                  at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:125)
                  at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
                  at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
                  at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
                  at okhttp3.RealCall.execute(RealCall.java:77)
                  at org.goldenfs.payoffcalculator.advisor.requestHTTP(advisor.java:220)
                  at org.goldenfs.payoffcalculator.advisor.access$000(advisor.java:38)
                  at org.goldenfs.payoffcalculator.advisor$4.onClick(advisor.java:188)
                  at android.view.View.performClick(View.java:6261)
                  at android.widget.TextView.performClick(TextView.java:11180)
                  at android.view.View$PerformClick.run(View.java:23748)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6776)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

申请已终止。

请帮我解决这个问题。我非常感谢你的帮助...... :)

2 个答案:

答案 0 :(得分:2)

它会抛出错误,因为您尝试在MainThread上执行网络操作,这是不应该的。请添加以下行并尝试

  public void onViewCreated(View view, Bundle savedInstanceState) 
    {
        int SDK_INT = android.os.Build.VERSION.SDK_INT;
        if (SDK_INT > 8) 
        {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
            //your codes here

        }
    }

您可以在AsyncTask中调用不在MainThread上运行的方法。

private class YourAsyncTaskName extends AsyncTask<String, Void, String> {

        String data;
        public YourAsyncTaskName(String data){
            this.data= data;
         }

        @Override
        protected String doInBackground(String... params) {
            requestHTTP(data);
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }

现在执行你的AsyncTask

submitRequest.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if ( firstName.getText().toString().length() == 0 ) {
                firstName.setError("Please enter your first name!");
            }
            if ( firstName.getText().toString().length() != 0 ) {

                Toast.makeText(getApplicationContext(), firstName.getText().toString(), Toast.LENGTH_SHORT).show();

                new YourAsyncTaskName(firstName.getText().toString()).execute();


            } else {

            }
        }
    });

答案 1 :(得分:2)

  

android.os.NetworkOnMainThreadException                     在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)

您应该使用 THREAD

    //A thread is a thread of execution in a program.
    // The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
    Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {
            try
            {

                            OkHttpClient httpClient = new OkHttpClient();
                            String url = "https://www.example.com/action.php";

                            RequestBody formBody = new FormBody.Builder()
                                    .add("first_name", first_name)
                                    .build();
                            Request request = new Request.Builder()
                                    .url(url)
                                    .post(formBody)
                                    .build();
                            Response response = null;
                            try {
                                response = httpClient.newCall(request).execute();
                                if (response.isSuccessful()) {
                                    Toast.makeText(getApplicationContext(), firstName.getText().toString(), Toast.LENGTH_SHORT).show();
                                }

                            } catch (IOException e) {

                            }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    thread.start();

来自OkHttp