Home > Mobile >  HttpURLConnection in android app not working [duplicate]
HttpURLConnection in android app not working [duplicate]

Time:09-17

I've tried this code in IntelliJ IDEA and it works perfectly , returning responseCode and responseMessage , but when I copy same code to Android Studio , it gives me a bunch of errors , and doesnt return nothing. It all works until i try to get some type of response( Code , message , InputStreams , etc )

                BufferedReader reader;
                String line;
                StringBuffer responseContent = new StringBuffer();
                try
                {
                    URL url = new URL("...");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);


                    Log.i("CODE " ,"" conn.getResponseCode());
                    Log.i("MSG "  , conn.getResponseMessage());

                    reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    while((line = reader.readLine()) != null)
                    {
                        responseContent.append(line);
                    }
                    reader.close();
                    Log.i("OUTPUT " , responseContent.toString());

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

ERRORS

/System.err: android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1605)
        at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
        at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
        at java.net.InetAddress.getAllByName(InetAddress.java:1152)
        at com.android.okhttp.Dns$1.lookup(Dns.java:41)
        at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:178)
        at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:144)
W/System.err:     at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:86)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:176)
        at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
W/System.err:     at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
        at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
        at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:542)
W/System.err:     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:106)
        at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:30)
        at com.example.practiceapp.MainActivity$1.onClick(MainActivity.java:50)
        at android.view.View.performClick(View.java:7448)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
        at android.view.View.performClickInternal(View.java:7425)
        at android.view.View.access$3600(View.java:810)
        at android.view.View$PerformClick.run(View.java:28305)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

CodePudding user response:

You are doing network call in the main thread.

User AsyncTask

new AsyncTask<String,String,String>(){

@Override
protected String doInBackground(String... params) {
    
    //Your HTTP Request goes here
    
    return response;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    Log.i("UpdateJSON ", s);
    if(!s.equalsIgnoreCase("null") || !s.equalsIgnoreCase(""))
        writeManifestJSON(s);
}
}.execute();

OR

Use Thread

Thread thread = new Thread(new Runnable() {
    
    @Override
    public void run() {
        try  {
            //Your HTTP Request goes here
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

thread.start(); 

CodePudding user response:

You are calling this code in main thread try this

public void onViewCreated() 
{
    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

    }
}
  • Related