Search code examples
androidandroidhttpclientnetworkonmainthreadokhttp

HTTP Request Not Working?


I'm trying to create an app which will send some data to a web server when a button will be clicked and the data will be from the form. The data types are first name, last name and others. I'm a beginner developer and trying OKHTTPFClient plugin for sending HTTP request from the app. What I need is on click the form data will be send to the PHP and then PHP will give a success response which will then the app get and then the activity will be redirected to thank you activity. Here's the code I'm trying now -

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 {

            }
        }
    });

And here is the method for 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) {

    }
}

UPDATE :

Here's the errors showing on Android Run section -

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)

Application terminated.

Please help me to solve that issue. I really appreciate your help... :)


Solution

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

    You should use 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();
    

    From OkHttp.