-1

Every time I try some HTTPRequest examples from the internet, they won't work. So I mixed it up together, and made this: ` package com.devwild.httpwerkgodverdomme;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public static void getdata(View view) {
try {
URL url = new URL("http://devwild.nl/zermelo/calll.php?school=carmelhengelo&koppelcode=742138265794");
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
String encoding = con.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
int len = 0;
while ((len = in.read(buf)) != -1) {
baos.write(buf, 0, len);
}
String body = new String(baos.toByteArray(), encoding);
System.out.println(body);
}catch(IOException e) {
e.printStackTrace();
}
}
}`

It works fine in plain JAVA (javac and compiling), but when I put it in android studio it just doesn't work an gives me this error:

LOG

How can I fix it?

Note: YES, I did try a lot of examples on the internet (~50)

2 Answers2

0

You're getting NetworkOnMainThreadException. Fix it by simply putting your network related calls either in a new Thread or in the AsyncTask.

You can find out how it's done in the link I provided, or by simply googling it.

Community
  • 1
  • 1
Vucko
  • 7,371
  • 2
  • 27
  • 45
  • 1
    Finally fixed this! Thanks, this is the code I'm using: http://pastebin.com/dQ7JAqnF –  Apr 23 '16 at 10:39
0

Make sure you have permission to access network and internet in Manifest and code: http://developer.android.com/training/basics/network-ops/connecting.html and start it in new thread or asynctask: http://developer.android.com/guide/components/processes-and-threads.html

Omid Aminiva
  • 667
  • 5
  • 14