UnknownHostException when sending HTTPS/HTTP POST from Android Device - android

I'm trying to create an HTTP POST to Google servers to obtain the ClientLogin Auth (as described here). The source code for the post is not a real mystery and I found it here. (I'm sure my post works because using CURL I obtain the Auth)
The method is very simple and I've modified the values accordingly, however, I'm getting the following exception when I execute the following line:
HttpResponse response = client.execute(post);
06-17 13:44:05.645: WARN/System.err(768): java.net.UnknownHostException: www.google.com
06-17 13:44:05.645: WARN/System.err(768): at java.net.InetAddress.lookupHostByName(InetAddress.java:506)
06-17 13:44:05.645: WARN/System.err(768): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
06-17 13:44:05.645: WARN/System.err(768): at java.net.InetAddress.getAllByName(InetAddress.java:256)
06-17 13:44:05.645: WARN/System.err(768): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
06-17 13:44:05.645: WARN/System.err(768): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
06-17 13:44:05.645: WARN/System.err(768): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
06-17 13:44:05.645: WARN/System.err(768): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
06-17 13:44:05.645: WARN/System.err(768): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
06-17 13:44:05.645: WARN/System.err(768): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
06-17 13:44:05.645: WARN/System.err(768): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
etc.
etc.
etc…
(irrelevant log omitted).
After trying various combinations of code (found on google and here), different URLs too (with or without HTTPS), regular HTTP too, etc. I've decided to try the following:
try {
InetAddress address = InetAddress.getByName("http://www.google.com");
} catch (UnknownHostException e) {
e.printStackTrace();
}
and I get the same error: (trimmed the irrelevant parts too)
06-17 13:53:07.445: WARN/System.err(820): java.net.UnknownHostException: http://www.google.com
06-17 13:53:07.449: WARN/System.err(820): at java.net.InetAddress.lookupHostByName(InetAddress.java:506)
06-17 13:53:07.449: WARN/System.err(820): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
06-17 13:53:07.449: WARN/System.err(820): at java.net.InetAddress.getByName(InetAddress.java:325)
Now I've sure restarted Eclipse, The Phone, I've even forgotten the Wi-Fi and re-created it. I'm using a STATIC IP address on the phone with either Google's DNS or OpenDNS (i've swapped them to try). Internet on the phone works, other applications work.
I do have
<uses-permission android:name="android.permission.INTERNET" />
on my Manifest in the correct spot (inside Application), in fact I also have "android.permission.ACCESS_FINE_LOCATION" but that doesn't change anything.
Device
It's a fresh Nexus-S (unlocked) with Android 2.3.4.
Code that Fails
This is the method in question: (see line HttpResponse response = client.execute(post);)
Please note that I've removed the "real values" but rest assured the correct values are in the original code.
public void getAuthentification(View view) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(
"https://www.google.com/accounts/ClientLogin");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("Email", prefs.getString(
"user", "undefined")));
nameValuePairs.add(new BasicNameValuePair("Passwd", prefs
.getString("password", "undefined")));
nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
nameValuePairs.add(new BasicNameValuePair("source",
"Google-cURL-Example"));
nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
Log.e("HttpResponse", line);
if (line.startsWith("Auth=")) {
Editor edit = prefManager.edit();
edit.putString(AUTH, line.substring(5));
edit.commit();
String s = prefManager.getString(AUTH, "n/a");
Toast.makeText(this, s, Toast.LENGTH_LONG).show();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
What am I missing?

Ok, after reading this answer and in contrary to what I've read in other google results, the…
<uses-permission android:name="android.permission.INTERNET" />
…must be outside the application.
I have it:
<!-- General Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
Now it works.

Do you try it on Device? Sometimes what happens is that emulator fails to resolve DNS and gives an error message.

Related

java.net.UnknownHostException in Android when trying to reach graph.facebook.com

I have an android app, and I try to get information from Facebook. I use an http get request and actually worked out great in one instance (when I try to get a user mutual friends list).
However, I have attempted to get the user events, and for some reason I get this exception. The funny thing is that the URL works great (tested it in a browser while debugging) and as mentioned - I use the same method in another place in my code to get something and it works. I'm completely losing it trying to figure out what's wrong!
Here's the code:
String accessToken = Session.getActiveSession().getAccessToken();
String query = "https://graph.facebook.com/me/events/attending?fields=id,name,location,venue,start_time,end_time,privacy&access_token=" + accessToken;
HttpGet get = new HttpGet(query);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(get);
String result = EntityUtils.toString(response.getEntity());
JSONObject eventsJsonObj = new JSONObject(result);
JSONArray eventsArray = eventsJsonObj.getJSONArray("data");
for (int i=0; i < eventsArray.length(); i++) {
// do something with event
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EDIT: here's the stack trace and the url as taken in debug and checked in browser (replacing of course the access token with [access_token]). btw, you can try the url yourself with an access token from the graph api explorer
URL: https://graph.facebook.com/me/events/attending?fields=id,name,location,venue,start_time,end_time,privacy&access_token=[access_token]
06-17 15:07:17.684: W/System.err(22733): java.net.UnknownHostException
06-17 15:07:17.684: W/System.err(22733): at org.apache.http.impl.conn.DefaultClientConnectionOperator.getAllByName(DefaultClientConnectionOperator.java:272)
06-17 15:07:17.684: W/System.err(22733): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:153)
06-17 15:07:17.684: W/System.err(22733): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:167)
06-17 15:07:17.689: W/System.err(22733): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:125)
06-17 15:07:17.689: W/System.err(22733): at org.apache.http.impl.client.DefaultRequestDirector.executeOriginal(DefaultRequestDirector.java:1171)
06-17 15:07:17.689: W/System.err(22733): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:637)
06-17 15:07:17.689: W/System.err(22733): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
06-17 15:07:17.689: W/System.err(22733): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
06-17 15:07:17.694: W/System.err(22733): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
06-17 15:07:17.694: W/System.err(22733): at
After a lot of aggression towards Eclipse, I finally figured out the dumb (yet reasonable) mistake I made.
I called the request on the main thread, which is something everybody knows not to do. So that was the issue… if anyone ever runs into.
Facebook takes get requests.

org.apache.http.client.HttpResponseException: Not Found error in android

I am creating application where the user enters data to search and then application sends it to server and then server sends search result back to the client.
I am getting error with i am not able to understand what it means.
here is my networking code from there application and here is link to full code
public class GetDatafromDB_Searchresult {
public String getDataFromDB() {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://192.168.0.106/test/search1.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
nameValuePairs.add(new BasicNameValuePair("carat1", strcolor1.toString().trim()));
nameValuePairs.add(new BasicNameValuePair("carat2", strcolor2.toString().trim()));
nameValuePairs.add(new BasicNameValuePair("color1", strclarity1.toString().trim()));
nameValuePairs.add(new BasicNameValuePair("color2", strclarity2.toString().trim()));
nameValuePairs.add(new BasicNameValuePair("cut1", strcut1.toString().trim()));
nameValuePairs.add(new BasicNameValuePair("cut2", strcut2.toString().trim()));
nameValuePairs.add(new BasicNameValuePair("shape1", strshape1.toString().trim()));
nameValuePairs.add(new BasicNameValuePair("shape2", strshape2.toString().trim()));
nameValuePairs.add(new BasicNameValuePair("stones", strstone.toString().trim()));
// $Edittext_value = $_POST['Edittext_value'];
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response = httpclient.execute(httppost);
HttpEntity entity= response.getEntity();
{
if(entity!=null)
{
entity.consumeContent();
}
}
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response1 = httpclient.execute(httppost, responseHandler);
System.out.println("Response : " + response1);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception : " + e.getMessage());
}
return response1;
}
}
here is my server side code
<?php
$hostname_localhost ="localhost";
$database_localhost ="testdb";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$carat1 = $_POST['carat1'];
$carat2 = $_POST['carat2'];
$color1 = $_POST['color1'];
$color2 = $_POST['color2'];
$cut1 = $_POST['cut1'];
$cut2 = $_POST['cut2'];
$shape1 = $_POST['shape1'];
$shape2 = $_POST['shape2'];
$stones = $_POST['stones'];
$query_search ="Select * from search1 where
carats = $carat1 and carats = $carat2 and
color = '$color1' or color = '$color2' and
cut = '$cut1' or cut = '$cut2' and
shape = '$shape1' or shape = '$shape2' and
stone ='$stones'";
$query_exec = mysql_query($query_search) or die(mysql_error());
while($row=mysql_fetch_assoc($query_exec))
$json_output[]=$row;
echo json_encode($json_output);
mysql_close();
?>
here is my error from logcat
06-03 14:35:31.269 18943-19053/com.diamond.traders W/System.err﹕ org.apache.http.client.HttpResponseException: Not Found
06-03 14:35:31.269 18943-19053/com.diamond.traders W/System.err﹕ at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:71)
06-03 14:35:31.269 18943-19053/com.diamond.traders W/System.err﹕ at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:59)
06-03 14:35:31.269 18943-19053/com.diamond.traders W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:657)
06-03 14:35:31.269 18943-19053/com.diamond.traders W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627)
06-03 14:35:31.269 18943-19053/com.diamond.traders W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
06-03 14:35:31.269 18943-19053/com.diamond.traders W/System.err﹕ at com.diamond.traders.Search_result$GetDatafromDB_Searchresult.getDataFromDB(Search_result.java:692)
06-03 14:35:31.269 18943-19053/com.diamond.traders W/System.err﹕ at com.diamond.traders.Search_result$1.run(Search_result.java:88)
06-03 14:35:31.269 18943-19053/com.diamond.traders W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
06-03 14:35:31.269 18943-19053/com.diamond.traders I/System.out﹕ Exception : Not Found
06-03 14:35:31.269 18943-18943/com.diamond.traders E/log_tag﹕ Error parsing data org.json.JSONException: End of input at character 0 of
I'm not sure but I suggest to you firstable to replace this line
nameValuePairs = new ArrayList<NameValuePair>(2);
by
nameValuePairs = new ArrayList<NameValuePair>();
And in your web service, you have to work with POST not GET.

Android- org.apache.http.ProtocolException: The server failed to respond with a valid HTTP response

I am trying to send a HTTP post request to a REST service through my android app and the client runs as an async task. Here is the client:
#Override
protected Void doInBackground(Void... params) {
String address = "http://xxx.xx.x.xxx:8080/rest/manageUser/create";
StringBuilder stringBuilder = null;
ArrayList<NameValuePair> postParameters;
try {
HttpPost httpPost = new HttpPost(address);
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("userId", userId));
postParameters.add(new BasicNameValuePair("firstName", firstName));
postParameters.add(new BasicNameValuePair("lastName", lastName));
postParameters.add(new BasicNameValuePair("mobileNumber",
mobileNumber));
postParameters.add(new BasicNameValuePair("loginStatus",
loginStatus));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
// System.out.println(stringBuilder);
} catch (Exception e) {
e.printStackTrace();
}
JSONObject jobj = null;
try {
jobj = new JSONObject(stringBuilder.toString());
System.out.println(jobj.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
Also when I create the client as an standalone java class it works fine. But when I use it from my Android app as an async task as above, I get the following exception:
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.example.hello.service.client.CreateUser.doInBackground(CreateUser.java:64)
at com.example.hello.service.client.CreateUser.doInBackground(CreateUser.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: org.apache.http.ProtocolException: The server failed to respond with a valid HTTP response
at org.apache.http.impl.conn.DefaultResponseParser.parseHead(DefaultResponseParser.java:93)
at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:174)
at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:180)
at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:235)
at org.apache.http.impl.conn.AbstractClientConnAdapter.receiveResponseHeader(AbstractClientConnAdapter.java:259)
at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:279)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:121)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:428)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
... 10 more
org.json.JSONException: End of input at character 0 of
at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
at org.json.JSONTokener.nextValue(JSONTokener.java:97)
at org.json.JSONObject.<init>(JSONObject.java:155)
at org.json.JSONObject.<init>(JSONObject.java:172)
at com.example.hello.service.client.CreateUser.doInBackground(CreateUser.java:82)
at com.example.hello.service.client.CreateUser.doInBackground(CreateUser.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Can anyone suggest what could be the problem. Also in my rest service, I am recieving the data with the #FormParam . Any help would be appreciated.
I think you are using wrong HTTP method. Just check HTTP Method whether it is correct or not and just try to get json that is going as part of request body.

getting server response with HttpResponse

i am making a file and database uploader in android and my upload Code is:
public int uploadFile(ArrayList<String> sourceFileUri, String info, String latitude, String longitude, String id) throws IOException {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://10.0.2.2/deliverysystem/order/add");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("returnformat", new StringBody("json"));
System.out.println(sourceFileUri.size());
for(int i=0;i<sourceFileUri.size();i++){
String sourceFile = sourceFileUri.get(i);
entity.addPart("uploaded_file"+(i+1), new FileBody(new File(sourceFile)));
}
entity.addPart("fld_delivery_id", new StringBody(id));
entity.addPart("fld_delivery_location", new StringBody(info));
entity.addPart("fld_latitude", new StringBody(latitude));
entity.addPart("fld_longitude", new StringBody(longitude));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);....
and when the code reaches last code
HttpResponse response = httpClient.execute(httpPost, localContext);
it throws an error
E/org.apache.http.conn.HttpHostConnectException(4740): Connection to http://10.0.2.2:8080 refused'
all the upload task is done but when executing the last code it doesnt return the response code but goes to exception part. i cant understand what is happening can anybody help me?
Here is complete log cat
E/org.apache.http.conn.HttpHostConnectException(4318): Connection to http://localhost refused
E/org.apache.http.conn.HttpHostConnectException(4318): org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused
E/org.apache.http.conn.HttpHostConnectException(4318): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
E/org.apache.http.conn.HttpHostConnectException(4318): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
E/org.apache.http.conn.HttpHostConnectException(4318): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
E/org.apache.http.conn.HttpHostConnectException(4318): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
E/org.apache.http.conn.HttpHostConnectException(4318): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
E/org.apache.http.conn.HttpHostConnectException(4318): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
E/org.apache.http.conn.HttpHostConnectException(4318): at com.example.android.photobyintent.ViewRecipients.uploadFile(ViewRecipients.java:325)
E/org.apache.http.conn.HttpHostConnectException(4318): at com.example.android.photobyintent.ViewRecipients$1.run(ViewRecipients.java:238)
E/org.apache.http.conn.HttpHostConnectException(4318): at java.lang.Thread.run(Thread.java:856)
E/org.apache.http.conn.HttpHostConnectException(4318): Caused by: java.net.ConnectException: failed to connect to /127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
E/org.apache.http.conn.HttpHostConnectException(4318): at libcore.io.IoBridge.connect(IoBridge.java:114)
E/org.apache.http.conn.HttpHostConnectException(4318): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
E/org.apache.http.conn.HttpHostConnectException(4318): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
E/org.apache.http.conn.HttpHostConnectException(4318): at java.net.Socket.connect(Socket.java:842)
E/org.apache.http.conn.HttpHostConnectException(4318): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
E/org.apache.http.conn.HttpHostConnectException(4318): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
E/org.apache.http.conn.HttpHostConnectException(4318): ... 8 more
E/org.apache.http.conn.HttpHostConnectException(4318): Caused by: libcore.io.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
E/org.apache.http.conn.HttpHostConnectException(4318): at libcore.io.Posix.connect(Native Method)
E/org.apache.http.conn.HttpHostConnectException(4318): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
E/org.apache.http.conn.HttpHostConnectException(4318): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
E/org.apache.http.conn.HttpHostConnectException(4318): at libcore.io.IoBridge.connect(IoBridge.java:112)
E/org.apache.http.conn.HttpHostConnectException(4318): ... 13 more
Did you add this to the manifest file?
<uses-permission android:name="android.permission.INTERNET" />
Or maybe the url should be:
"http://10.0.2.2/deliverysystem/order/add/"
I added a "/" at the end of the url
First add this to your the manifest file
<uses-permission android:name="android.permission.INTERNET" />
& then
Try this code,
Do some Change As per ur Requirement instead of above & file upload put in Asynctask Method that not Affect to your Application Main Thread
protected String doInBackground(String... args) {
String ServerResponse = "";
mDbHelper = new DbAdapter(ct);
mDbHelper.open();
ImageUploadEntity entity = new ImageUploadEntity();
List<ImageUploadEntity> imagedatas = mDbHelper
.fetchImageByModuleId(Submission_id);
mDbHelper.close();
Totalfilecount = imagedatas.size();
if (Totalfilecount != 0) {
for (int j = 0; j < imagedatas.size(); j++) {
entity = imagedatas.get(j);
String path = entity.getFilecontent();
final HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://10.0.2.2/deliverysystem/order/add");
HttpContext localContext = new BasicHttpContext();
// Indicate that this information comes in parts (text and file)
final MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
final File file = new File(path);
if (file.exists()) {
String filename = Common
.MillisecondsToDateFORFileName(System
.currentTimeMillis());
FileBody fileBody = new FileBody(file, "image/png");
reqEntity.addPart("filecontent", fileBody);
try {
// The rest of the data
reqEntity.addPart("fld_delivery_id", new StringBody(id));
reqEntity.addPart("fld_delivery_location", new StringBody(info));
reqEntity.addPart("fld_latitude", new StringBody(latitude));
reqEntity.addPart("fld_longitude", new StringBody(longitude));
reqEntity.addPart("returnformat", new StringBody("json"));
postRequest.setEntity(reqEntity);
ServerResponse = httpClient.execute(postRequest,localContext)………
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
return ServerResponse;
}

HttpHostConnectException: Connection refused Android

I am trying to connect via HttpPost and send a username and password to a website and then receive a string from that website. I have tried various methods that have worked for me in the past but now when I send the username and password identifiers the app times out for as long as 4 minutes and then spits out the following exception:
07-16 16:32:32.897: W/System.err(632): Unable to connect to the server
07-16 16:32:32.907: W/System.err(632): org.apache.http.conn.HttpHostConnectException: Connection to http://devdashboard.company refused
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
07-16 16:32:32.917: W/System.err(632): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
07-16 16:32:32.927: W/System.err(632): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
07-16 16:32:32.927: W/System.err(632): at company.android.dashboard.app.HttpHelperAndroid.sendToHttp(HttpHelperAndroid.java:66)
07-16 16:32:32.927: W/System.err(632): at company.android.dashboard.app.DashboardAppActivity.goToDashboard(DashboardAppActivity.java:62)
07-16 16:32:32.927: W/System.err(632): at java.lang.reflect.Method.invokeNative(Native Method)
07-16 16:32:32.937: W/System.err(632): at java.lang.reflect.Method.invoke(Method.java:511)
07-16 16:32:32.937: W/System.err(632): at android.view.View$1.onClick(View.java:3039)
07-16 16:32:32.947: W/System.err(632): at android.view.View.performClick(View.java:3511)
07-16 16:32:32.947: W/System.err(632): at android.view.View$PerformClick.run(View.java:14105)
07-16 16:32:32.947: W/System.err(632): at android.os.Handler.handleCallback(Handler.java:605)
07-16 16:32:32.957: W/System.err(632): at android.os.Handler.dispatchMessage(Handler.java:92)
07-16 16:32:32.957: W/System.err(632): at android.os.Looper.loop(Looper.java:137)
07-16 16:32:32.967: W/System.err(632): at android.app.ActivityThread.main(ActivityThread.java:4424)
07-16 16:32:32.977: W/System.err(632): at java.lang.reflect.Method.invokeNative(Native Method)
07-16 16:32:32.977: W/System.err(632): at java.lang.reflect.Method.invoke(Method.java:511)
07-16 16:32:32.977: W/System.err(632): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-16 16:32:32.987: W/System.err(632): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-16 16:32:32.987: W/System.err(632): at dalvik.system.NativeStart.main(Native Method)
07-16 16:32:32.987: W/System.err(632): Caused by: java.net.ConnectException: failed to connect to /50.19.240.232 (port 80): connect failed: ETIMEDOUT (Connection timed out)
07-16 16:32:32.997: W/System.err(632): at libcore.io.IoBridge.connect(IoBridge.java:114)
07-16 16:32:32.997: W/System.err(632): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
07-16 16:32:32.997: W/System.err(632): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
07-16 16:32:33.007: W/System.err(632): at java.net.Socket.connect(Socket.java:842)
07-16 16:32:33.007: W/System.err(632): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
07-16 16:32:33.017: W/System.err(632): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
07-16 16:32:33.017: W/System.err(632): ... 22 more
07-16 16:32:33.027: W/System.err(632): Caused by: libcore.io.ErrnoException: connect failed: ETIMEDOUT (Connection timed out)
07-16 16:32:33.047: W/System.err(632): at libcore.io.Posix.connect(Native Method)
07-16 16:32:33.047: W/System.err(632): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
07-16 16:32:33.047: W/System.err(632): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
07-16 16:32:33.057: W/System.err(632): at libcore.io.IoBridge.connect(IoBridge.java:112)
07-1
6 16:32:33.057: W/System.err(632): ... 27 more
Internet permission IS enabled in my XML manifest file
My current implementation goes like this:
String LOGIN = "email#gmail.com";
String PASSWORD ="password1";
//JSONObject to send the username and pw
JSONObject json = new JSONObject();
//put the path in the JSONArray object
JSONArray vect = new JSONArray();
vect.put("company Android Library");
vect.put("Rocket Ship");
int duration = 50;
try {
json.put("email", LOGIN);
json.put("password", PASSWORD);
json.put("json", "true");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d(TAG, "ABOUT TO SEND:" + json.toString());
JSONObject inJson = HttpHelperAndroid.sendToHttp(json, "http://devdashboard.company/login");
if(inJson != null)
{
Log.d(TAG, "RECIEVED the JSON:" + inJson.toString());
}
else
Log.d(TAG, "THE RESPONSE WAS NULL");
}
And the HttpHelperAndroid class looks like so:
public class HttpHelperAndroid
{
private static final String TAG = "HttpHelperAndroid";//TAG for the LogCat(debugging)
private static boolean responseSuccessful = true;
/**
* sends the JSONObject parameter to the desired URL parameter and gets the response
*
* #param url the URL to which the JSONObject should be sent
* #param jsonObjOut the JSONObject that is to be sent
* #return the response from the server as a JSONObject
*/
public static JSONObject sendToHttp(JSONObject jsonObjOut, String url) {
responseSuccessful = true;
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(url);
//convert the JSONObject to a string
StringEntity se;
//set our StringEntity to the JSONObject as a string
se = new StringEntity(jsonObjOut.toString());
// Set HTTP params
httpRequest.setEntity(se);
httpRequest.setHeader("Accept", "application/json");
httpRequest.setHeader("Content-type", "application/json");
httpRequest.setHeader("Accept-Encoding", "gzip"); //for gzip compression
//get the current time
long oldTime = System.currentTimeMillis();
HttpResponse response = null;
try
{
//execute the http request and get the response
response = (HttpResponse) httpClient.execute(httpRequest);
}
catch(HttpHostConnectException e)
{
System.err.println("Unable to connect to the server");
e.printStackTrace();
responseSuccessful = false;
}
//only continue executing if we got a response from the server
if(responseSuccessful)
{
//print how long the response took to the LogCat if it's on
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-oldTime) + "ms]");
// Get hold of the response entity (-> the data):
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream in = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
in = new GZIPInputStream(in);
}
// convert content stream to a String
String resultString= streamToString(in);
//close the stream
in.close();
// convert the String into a JSONObject
JSONObject jsonObjRecv = new JSONObject(resultString);
//take a peak at the JSONObject we got back if the LogCat is on
Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
//return the JSONObject we got back from the server
return jsonObjRecv;
}
}
}
//catch any exception that was thrown
catch (Exception e)
{
//Print the exception
e.printStackTrace();
}
return null;
}
private static String streamToString(InputStream is)
{
//create a new BufferedReader for the input stream
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
//create a new StringBuilder to append the lines
StringBuilder sb = new StringBuilder();
//initialize an empty string
String line = null;
try
{
//iterate as long as there is still lines to be read
while ((line = reader.readLine()) != null)
{
//append the line and a newline character to our StringBuilder
sb.append(line + "\n");
}
}
//catch an IOException and print it
catch (IOException e) {
e.printStackTrace();
}
//close the stream when we're done
finally
{
try
{
is.close();
}
//catch and print an exception if it's thrown
catch (IOException e)
{
e.printStackTrace();
}
}
//return the stream converted to a string
return sb.toString();
}
}
And here is my XML just for kicks:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="company.android.dashboard.app"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk android:minSdkVersion="7" />
<application
android:icon="#drawable/company_android_ico"
android:label="#string/app_name" >
<activity
android:name=".DashboardAppActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I have used the HttpHelper class in past projects and it has worked for me, in addition I tried to implement this using nameValuePairs:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", "email#gmail.com"));
nameValuePairs.add(new BasicNameValuePair("password", "password1"));
nameValuePairs.add(new BasicNameValuePair("json", "true"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
And this yielded the same result.
Could this somehow be a certificate thing? or perhaps something to do with a corrupt XML file( I tried remaking the project and the xml file) Android HTTP Connection refused
Or maybe some sort of Android hosts file issue?
I'm open to any suggestions!
I have examined this from a lot of angles and I'm happy to provide any other information that would be helpful! I really appreciate your time!
NOTE: The url is a dummy url, and not the actual one I am connecting to, for security reasons. I am able to curl the actual website from the command line with the parameters and it works and I am also able to login normally from the web browser.
EDIT I have identified the problem! But not the solution unfortunately. So the issue is that I am using a dev server url that doesn't have a domain entry on the global DNS server. So to fix this I somehow need to edit the hosts file on my Android device/in the emulator...does anyone know how this can be done legitimately?
I have identified the problem! So the issue is that I am using a dev server url that doesn't have a domain entry on the global DNS server.
So there are two possible solutions to this issue:
1) Editing the hosts file on the Android device (requires rooting your phone): How to change the hosts file on android
2) Getting the server registered on the global DNS server.
(also hard to do if you're not responsible for the url)
Anyways I hope this helps someone else too!
Please follow these solution may be among these one solve your issue.
1> check your manifest file internet permission there or not.
2> check your url with browser by rest client and pass the appropriate request.
3> open the url in mobile like:- http://your ip address/port that's it just for checking do you have a permission or not to open this url in mobile.
There are a few possibilities
1) the url is incorrect "http://devdashboard.company/login" is not right. At least check in browser.
ping the host as well.
2) This should be an https connection instead.
3) there is some certification required.
4) You are missing a port number. or domain has not been setup correctly.
perhaps port 80 the default is incorrect?
5) the call should not be a post.
In general you are either responsible for the server or you are not. It appears that it is some elses responsibility, and you should ask them what the correct url and parameters are. So its probably no ones fault, but you need to ask them about the connection to verify.
The other thing you can do is to try and see what the url looks like in an application that is succesfully connectiing. take a look that this.
The problem is in wifi sleeping.
Please use
WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiLock = wm.createWifiLock(WifiManager.WIFI_MODE_FULL , "MyWifiLock");
wifiLock.acquire();
and permission:
uses-permission android:name="android.permission.WAKE_LOCK";
This post is old, but it is the first result when googling this error. I encountered the same exception, and everything was completely correct in my code. I commented out the line containing the INTERNET permission in my AndroidManifest.xml, ran the app, clicked/tapped my button to send the HTTP request and get the exception, closed the app, went back to the manifest, uncommented the permission line, ran the app again, and the exception was resolved!
This kind of bugs in 2015 (and in "advanced" tools like the latest compile tools for Android API 21, and Intellij IDEA 14) drives me mad! You are approaching your deadline, and this sort of bugs completely disrupts your work!

Categories

Resources