How do I do a HTTP GET in Java (android?

Http Get using Android HttpURLConnection

  • I'm new to Java and Android development and try to create a simple app which should contact a web server and add some data to a database using a http get. When I do the call using the web browser in my computer it works just fine. However, when I do the call running the app in the Android emulator no data is added. I have added Internet permission to the app's manifest. Logcat does not report any problems. Can anyone help me to figure out what's wrong? Here is the source code: package com.example.httptest; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; public class HttpTestActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = new TextView(this); setContentView(tv); try { URL url = new URL("http://www.mysite.se/index.asp?data=99"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.disconnect(); tv.setText("Hello!"); } catch (MalformedURLException ex) { Log.e("httptest",Log.getStackTraceString(ex)); } catch (IOException ex) { Log.e("httptest",Log.getStackTraceString(ex)); } } }

  • Answer:

    Try getting the input stream from this you can then get the text data as so:- URL url; try { url = new URL("http://www.mysite.se/index.asp?data=99"); HttpURLConnection urlConnection = (HttpURLConnection) url .openConnection(); InputStream in = urlConnection.getInputStream(); InputStreamReader isw = new InputStreamReader(in); int data = isw.read(); while (data != -1) { char current = (char) data; data = isw.read(); System.out.print(current); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } You can probably use other inputstream readers such as buffered reader also. The problem is that when you open the connection - it does not 'pull' any data.

user1119112 at Stack Overflow Visit the source

Was this solution helpful to you?

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.