I am trying to call a URL in android using
HttpClient mClient= new DefaultHttpClient()
HttpGet get = new HttpGet("www.google.com ");
mClient.execute(get);
HttpResponse res = mClient.execute(get);
But, I did not get any response. How can I call URL in Android?
This is a complete example:
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(yourURL);
HttpResponse response = httpclient.execute(httpget);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
Log.v("My Response :: ", result);
use the url with the protocol "https://
"
"https://www.stackoverflow.com" instead of just "www.stackoverflow.com"
be sure to have this permission into your androidmanifest.xml
<uses-permission
android:name="android.permission.INTERNET" />
You must add <uses-permission android:name="android.permission.INTERNET"/>
in the AndroidManifest.xml file. Under <manifest>
element.
You are calling mClient.execute(get)
twice.
mClient.execute(get);
HttpResponse res = mClient.execute(get);
Use volley instead.
RequestQueue requestQueue = Volley.newRequestQueue(this);
String getUrl = "http://www.google.com";
StringRequest getRequest = new StringRequest(Request.Method.GET, getUrl, new Response.Listener<String>() {
@Override
public void onResponse (String response) {
Log.v(TAG, "GET response: " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse (VolleyError error) {
Log.v(TAG, "Volley GET error: " + error.getMessage());
}
});
requestQueue.add(getRequest);