8

I've tried the Jsoup.connect() example given on the Jsoup website and it works fine in Java.

For some reason, I can't make it work in Android Projects (Eclipse) even though I allow the Internet access permission in my AndroidManifest. The Jsoup library is installed correctly and I can work with Jsoup.parse() without any issues. Here's a few line of codes of what works in Java and also the permission in AndroidManifest.

Java

public static void main(String[] args){
    Document doc;
    try {
        doc = Jsoup.connect("http://google.ca/").get();
        String title = doc.title();
        System.out.print(title);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

AndroidManifest.xml

<uses-sdk android:minSdkVersion="12" />
<uses-permission android:name="android.permission.INTERNET"/>
<application

When I try to run it, it crashes and the log says:

01-09 20:19:30.560: E/AndroidRuntime(26839): java.lang.RuntimeException: 
Unable to start activity 
ComponentInfo{com.mrdroidinator.com/com.mrdroidinator.com.Parselhjmq}: android.os.NetworkOnMainThreadException
palacsint
  • 28,416
  • 10
  • 82
  • 109
user1139012
  • 81
  • 1
  • 1
  • 4
  • 01-09 20:19:30.560: E/AndroidRuntime(26839): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mrdroidinator.com/com.mrdroidinator.com.Parselhjmq}: android.os.NetworkOnMainThreadException – user1139012 Jan 10 '12 at 02:00
  • Nobody ever had this issue? I was also able to connect to the Yahoo! API (OAuth) via Java but it does not work within the android application in Eclipse. I guess these problems are related? – user1139012 Jan 12 '12 at 04:21
  • Are you behind a proxy by chance? Maybe the proxy isn't set for your Android project? – B. Anderson Feb 09 '12 at 20:47
  • it's easier now, see the sample recipe code here https://github.com/square/okhttp/blob/master/samples/guide/src/main/java/okhttp3/recipes/AccessHeaders.java – Someone Somewhere Feb 10 '16 at 14:35

1 Answers1

16

http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

The problem is that you are performing a network operation on the main thread, which is prohibited in API level 11+. This is because if you do it the UI is "frozen" until the document finishes downloading, so it is needed to perform such operations on a different thread, which doesn't affect UI perfomance.

This is how you start a new thread:

Thread downloadThread = new Thread() {
  public void run() {
    Document doc;
    try {
      doc = Jsoup.connect("http://google.ca/").get();
      String title = doc.title();
          System.out.print(title);
    } catch (IOException e) {
          e.printStackTrace();
    }
  }
};
downloadThread.start();
Alter Lagos
  • 12,090
  • 1
  • 70
  • 92
packito
  • 196
  • 1
  • 4