HTTP 请求不工作?

HTTP Request Not Working?

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

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 运行 部分中显示的错误 -

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.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[=12=]0(advisor.java:38)
                  at org.goldenfs.payoffcalculator.advisor.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)

应用程序终止。

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

它会抛出错误,因为您正在尝试对 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 {

            }
        }
    });

android.os.NetworkOnMainThreadException at 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.