简体   繁体   中英

Java: getting data from HTTP GET request

So in Java, I am trying to do an HTTP GET Request to get some JSON data from a webpage. The webpage is set up right that it just displays a JSON file as regular text as such:

{"checklist": [{"name": "Shutting Down Lab 37", "id": 2}, {"name": "Caging the Monkey", "id": 3}], "groupId": "1"}

That's the way it shows up right now if I just type the link directly into my browser.

I would like to pull this string of data from the HTTP Request and for testing purposes to just System.out.println .

I am getting a FATAL EXCEPTION: Main when I run my code. Please help!

public void GetRequest() throws MalformedURLException, IOException {
    String charset = "UTF-8";
    URLConnection connection = new URL(webpage).openConnection();
    InputStream response = connection.getInputStream();
    String contentType = connection.getHeaderField("Content Type");
    for (String param : contentType.replace(" ", "").split(";")) {
        if (param.startsWith("charset=")) {
            charset = param.split("=", 2)[1];
            break;
        }
    }

    if (charset != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset));
        try {
            for (String line; (line = reader.readLine()) != null;) {
                System.out.println(line);
            }
        }
            finally {
                try { reader.close(); } catch (IOException logOrIgnore) {}
            }
        }
    else {
    }
}

LogCat Errors

12-22 21:44:41.976: E/AndroidRuntime(1659): FATAL EXCEPTION: main
12-22 21:44:41.976: E/AndroidRuntime(1659): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.medusa.checkit/com.medusa.checkit.NewChecklistActivity}: android.os.NetworkOnMainThreadException
12-22 21:44:41.976: E/AndroidRuntime(1659):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at android.os.Looper.loop(Looper.java:137)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at android.app.ActivityThread.main(ActivityThread.java:4424)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at java.lang.reflect.Method.invokeNative(Native Method)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at java.lang.reflect.Method.invoke(Method.java:511)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at dalvik.system.NativeStart.main(Native Method)
12-22 21:44:41.976: E/AndroidRuntime(1659): Caused by: android.os.NetworkOnMainThreadException
12-22 21:44:41.976: E/AndroidRuntime(1659):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at com.medusa.checkit.ServerCall.GetRequest(ServerCall.java:22)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at com.medusa.checkit.NewChecklistActivity.onCreate(NewChecklistActivity.java:34)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at android.app.Activity.performCreate(Activity.java:4470)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
12-22 21:44:41.976: E/AndroidRuntime(1659):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
12-22 21:44:41.976: E/AndroidRuntime(1659):     ... 11 more

you should be getting a nullpointer exception. change your code to following to get the content type

connection.getHeaderField("Content-Type");

Yup the problem was NetworkOnMainThreadException and for those that don't know, you shouldn't run any network calls on the main thread.

I solved this by putting in an AsyncTask .

Thanks to @EJP for pointing this out!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM