Executing http in android not working - java

try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://www.google.com");
client.execute(request);//it fails at this line
Log.e("yo", "yo");
} catch (Exception e) {}
Have anyone figured out the problem please as I am experiencing the same issue.
My device is connected to the same network, pasting the URL in browser works however using HTTP doesn't.

try HttpPost method
Declare INTERNET PERMISSION IN manfiest file
httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost(URL);
HttpResponse res = null;
try {
res = httpclient.execute(httppost);
System.out.println("asa "+res);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}

Did you forget to add
<uses-permission android:name="android.permission.INTERNET" />
to your AndroidManifest.xml?

Are you running it on the same thread as your UI? You have to use separate thread for any network connection to prevent UI Blocking. You need to use AsyncTask in this case; and obviously, android Internet permission is needed.

Related

Java HTTP Request Stuck

I've never really used http requests in Java, I'm trying to make a request that would basically recreate this http://supersecretserver.net:8080/http://whateverwebsite.com
This server takes whatever website and returns only the text of the page in the body of the response.
The code is as follows:
public String getText(String webPage) throws ParseException, IOException{
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://supersecretserver.net:8080/" + "http://www.androidhive.info/2012/01/android-text-to-speech-tutorial/"));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String responseBody = "No text found on webpage.";
int responseCode = response.getStatusLine().getStatusCode();
switch(responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
}
}
System.out.println("Returning Response..");
System.out.println(responseBody);
return responseBody;
}
It seems to get stuck on
response = client.execute(request);
I'm not sure what the problems is, any insight would be helpful.
Seems likely that your HttpClient is not timing out, you can set a timeout value by following this example (from http://www.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/)
You just to have to consider a timeout value that makes sense for you.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeoutMillis);
HttpConnectionParams.setSoTimeout(httpParams, socketTimeoutMillis);
Also as your HttpClient is not connecting (since it's getting stuck) you should also take into consideration why is that happening (maybe you need to configure a proxy?)

Error HTTP 422 GET in Android

I'm trying to perform a GET request to the server that returns me a JSON file. But I am getting an error in the HTTP statusLine / 422. Anyone know why. Below I show how I'm doing
public void testConverteArquivoJsonEmObjetoJava() {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(
"http://safe-sea-4024.ppooiheroku4554566adffasdfasdfalaqwerpcp.com/crimes/mobilelist");
get.setHeader("Accept", "application/json");
get.setHeader("Content-type", "application/json");
get.getParams()
.setParameter("token",
"0V1AYFK12SeCZHYgXbNMew==$tRqPNplipDwtbD0vxWv6GPJIT6Yk5abwca3IJ88888a6JhMs=");
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(get);
String jsonDeResposta = EntityUtils.toString(httpResponse
.getEntity());
System.out.println();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Usually you do not specify a Content-Type header with a GET request. This header tells the server how to interpret the entity includes in the message. It is possible that the server side is expecting a JSON entity even though GET cannot include a body. Try removing the Content-Type header.
I tried the URL that you cleverly changed and got it to work fine. However, I did get a 422 when I specified a different token query parameter. Being that the status line is missing a phrase, I would assume that the Ruby application is generating it.
I managed to solve the problem. I was passing the parameter so wrong. According to this post [blog]:How to add parameters to a HTTP GET request in Android? "link". This method is used to that I kind of POST request
this method is correct
public void testConverteArquivoJsonEmObjetoJava() {
List<NameValuePair> params = new LinkedList<NameValuePair>();
params.add(new BasicNameValuePair("token","0V1AYFK12SeCZHYgXbNMew==$="));
String paramString = URLEncodedUtils.format(params, "utf-8");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(
"http://safep.com/crimes/mobilelist" + "?"
+ paramString);
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(get);
String jsonDeResposta = EntityUtils.toString(httpResponse
.getEntity());
System.out.println();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}`

Android Connection/SocketTimeOutException caught yet app still crash

Basically I'm trying to let user know when the app cannot reach the server/server down, while their phone internet/data connection is perfectly fine. So I set a timeout by following this post here: How to set HttpResponse timeout for Android in Java
It works great, except when the exception is caught correctly the app still crash instead of displaying the Toast message and return to the app screen. Notice that "Log.e("CONN TIMEOUT", e.toString());" logged correctly in logcat as: "CONN TIMEOUT org.apache.http.conn.ConnectTimeoutException: Connect to /192.168.11.60:80 timed out"
As requested, full logcat: http://pastebin.com/rpe8iKRi
// Making HTTP request
try {
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ConnectTimeoutException e) {
Toast.makeText(getApplicationContext(), "Server timeout", Toast.LENGTH_LONG).show();
Log.e("CONN TIMEOUT", e.toString());
} catch (SocketTimeoutException e) {
Toast.makeText(getApplicationContext(), "Server timeout", Toast.LENGTH_LONG).show();
Log.e("SOCK TIMEOUT", e.toString());
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
Log.e("OTHER EXCEPTIONS", e.toString());
}
got it resolved. missing throws Exception { at the end of the function. duhhh
thanks #Alin for good hint.

Downloading html source code and loading it

I found this code from here download html source android? . But when I try running it, my program keeps crashing. I have already added the internet permission in. Any ideas?
Edit: Here is the full error message. 08-02 00:16:47.364: E/EmbeddedLogger(1577): Error getting package label: com.jimmyc.lawrenceh.schedulinglookup
Edit2: It works on Android 2.2 but it doesn't work on Android 4.0/3.0.
private void initialize() {
//initialize variables here
try {
getHtml();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getHtml() throws ClientProtocolException, IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet("http://www.yahoo.com");
HttpResponse response = httpClient.execute(httpGet, localContext);
String result = "";
BufferedReader reader =
new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = null;
while ((line = reader.readLine()) != null){
result += line + "\n";
// Toast.makeText(Connect.this, line.toString(), Toast.LENGTH_LONG).show();
}
}
I think you are trying to download the HTML code in the UI Thread. Try to download it in the background, using AsynkTask
Edit. If you say that it works on Android 2.2 but it doesn't work on Android 4.0/3.0 I'm completely sure you are trying to download it in the UI thread. From Android 3.0, you can't do long process in the UI thread because you can block it. You must do the download in a different thread
PS. Sorry for my english.

Issue with AndroidHttpClient

I'm getting an IOException from my code using AndroidHttpClient. Is there something wrong with the code? The code is thrown whether I use port 80 or port 443, and with Http Schema http or https.
The exception is thrown at client.execute...it is a UnknownHostException exception..I'm not sure why. I can hit the service from the browser.
// declare locals
JSONObject joResponse = new JSONObject();
String response = "";
try
{
// prepare to execute
HttpHost target = new HttpHost(hostname, Const.HTTP_PORT, Const.HTTP_SCHEME);
HttpGet get = new HttpGet();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
AndroidHttpClient client = AndroidHttpClient.newInstance(null);
// execute
response = client.execute(target, get, responseHandler); // this is where the exception is thrown
joResponse = new JSONObject(response);
}
catch (ClientProtocolException e)
{
}
catch (IOException e)
{
}
catch(Exception e)
{
}
Do you have the internet permission declared in your app?
You need to add the following line to your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />

Categories

Resources