0

I copied this from Tutorialspoint and it seemed to not work for me.

I'm having the error E/HttpHandler: Exception: null

import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }
}

I believe this script basically checks the connection, and I did the following

HttpHandler sh = new HttpHandler();
    // Making a request to url and getting response
    String url = "http://api.androidhive.info/contacts/";
    String jsonStr = sh.makeServiceCall(url);

    if(jsonStr != null) {
        System.out.println("success");
    } else {
        System.out.println("failed");
    }

I checked the URL and it seemed to be accessible. I have no idea what causes the error. Also, I added the INTERNET permissions in the Manifest.

For the logs

android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1166)
    at java.net.InetAddress.lookupHostByName(InetAddress.java:425)
    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:259)
    at java.net.InetAddress.getAllByName(InetAddress.java:221)
    at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
    at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
    at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
    at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:278)
    at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:216)
    at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:391)
    at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:341)
    at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:199)
    at com.techdepot_ph.maco.iannounce.HttpHandler.makeServiceCall(HttpHandler.java:33)
    at com.techdepot_ph.maco.iannounce.SettingsFragment.syncdata(SettingsFragment.java:182)
    at com.techdepot_ph.maco.iannounce.SettingsFragment$5$1.onClick(SettingsFragment.java:151)
    at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
    at android.os.Handler.dispatchMessage(Handler.java:111)
    at android.os.Looper.loop(Looper.java:194)
    at android.app.ActivityThread.main(ActivityThread.java:5847)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1010)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
failed
Kamran Ahmed
  • 7,661
  • 4
  • 30
  • 55
Aaron Alfonso
  • 516
  • 1
  • 8
  • 27

2 Answers2

1

The part of the code where you are making this call is on the main thread. You are not allowed to make a network call from the main thread.

Try changing your code to something like:

new Thread(new Runnable() {
    HttpHandler sh = new HttpHandler();
    // Making a request to url and getting response
    String url = "http://api.androidhive.info/contacts/";
    String jsonStr = sh.makeServiceCall(url);

    if(jsonStr != null) {
        System.out.println("success");
    } else {
        System.out.println("failed");
    }
}).start();

You can also make use of helper classes like AsyncTask. Read more about multithreading here: Processes and Threads | Android Developers

Kamran Ahmed
  • 7,661
  • 4
  • 30
  • 55
1

I tested your code. it works fine but there is one silly mistake you are doing that you are calling web service from your Main-Thread.

There is NetworkOnMainThreadException

Replace your code with this :

new AsyncTask<Void, Void, String>()
        {
            ProgressDialog progressDialog;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();

                progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setCancelable(true);
                progressDialog.show();
            }

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

                HttpHandler sh = new HttpHandler();
                // Making a request to url and getting response
                String url = "http://api.androidhive.info/contacts/";
                String jsonStr = sh.makeServiceCall(url);

                if(jsonStr != null) {
                    System.out.println("success");
                } else {
                    System.out.println("failed");
                }

                return jsonStr;
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
                progressDialog.dismiss();

                System.out.println("result=="+result);
            }
        }.execute();
Vishal Chhodwani
  • 2,567
  • 5
  • 27
  • 40