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!
Related
I am working on android app that should send GCS registration token to .NET MVC service that is running on localhost. I am using android Emulator with API 23 version. I have eliminated nearly everything that can be wrong, URL and parameters I send at the moment are hardcoded and If I copy paste url into browser (and replace 10.0.2.2 with localhost obviously) everything works. I am using fiddler but request that is supposed to originate from android does not get registered.
What I am getting instead is IO exception on InputStream inputStream = connection.getInputStream(); line
1-18 18:26:28.305 3488-3524/gcm.play.android.samples.com.gcmquickstart
W/System.err: java.io.FileNotFoundException:
http://10.0.2.2:61594/api/Account/RegisterDevice?token=2342342&coordinates=12.012;13.1515
01-18 18:26:28.305
3488-3524/gcm.play.android.samples.com.gcmquickstart W/System.err:
at
com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
01-18 18:26:28.305
3488-3524/gcm.play.android.samples.com.gcmquickstart W/System.err:
at
gcm.play.android.samples.com.gcmquickstart.RegistrationIntentService.sendRegistrationToServer(RegistrationIntentService.java:108)
01-18 18:26:28.305
3488-3524/gcm.play.android.samples.com.gcmquickstart W/System.err:
at
gcm.play.android.samples.com.gcmquickstart.RegistrationIntentService.onHandleIntent(RegistrationIntentService.java:69)
01-18 18:26:28.305
3488-3524/gcm.play.android.samples.com.gcmquickstart W/System.err:
at
android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
01-18 18:26:28.306
3488-3524/gcm.play.android.samples.com.gcmquickstart W/System.err:
at android.os.Handler.dispatchMessage(Handler.java:102) 01-18
18:26:28.306 3488-3524/gcm.play.android.samples.com.gcmquickstart
W/System.err: at android.os.Looper.loop(Looper.java:148) 01-18
18:26:28.306 3488-3524/gcm.play.android.samples.com.gcmquickstart
W/System.err: at
android.os.HandlerThread.run(HandlerThread.java:61)
In watch connection.getResponseCode() status code is 400 (bad request) - but again server isn't even being hit.
I have configured following permissions in manifest:
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
Code that makes request:
StringBuffer chaine = new StringBuffer("");
try{
URL url = new URL("http://10.0.2.2:61594/api/Account/RegisterDevice?token=2342342&coordinates=12.012;13.1515");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("User-Agent", "");
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = rd.readLine()) != null) {
chaine.append(line);
}
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
Code from .NET Server
[AllowAnonymous]
[System.Web.Http.AcceptVerbs("GET", "POST")]
[System.Web.Http.HttpGet]
public void RegisterDevice(string token, string coordinates)
{
if (string.IsNullOrWhiteSpace(token))
{
throw new ArgumentNullException("Token is empty");
}
var data = new Data.EmergencyService();
if (data.AddUser(token, coordinates))
{
HttpContext.Current.Response.StatusCode = 200;
}
}
After I couldn't get fiddler to register request it made me to be completely lost.
Why can't I make request GET request from Andriod Studio which perfectly works in browser?
Ok for those who are wondering the reason for Android not being able to access PC localhost on http://10.0.2.2 was me running MVC service from Visual Studio in debug mode.
Once I have configured local IIS server and published website ( to local file system), Android was able to access it on http://10.0.2.2.
Hope this saves you some time.
Here I have a problem with getting request in Android.
I have run server program using webapp2 on my PC and I succeeded in sending request from itself to the server program.
However, when I tried to send request from my phone, it seems the program always jump the catch(Exception e) part. The three Log.e() works fine since I could see all of them in the log records. Can anyone tell me what might go wrong here? Is it the fire wall that my PC used to block the request? Thanks in advance.
PS: the variable resultString is the result I get from voice recognition.
try{
StringBuilder buf = new StringBuilder("http://192.168.1.100:9080/");
buf.append("?");
buf.append("content1="+URLEncoder.encode(resultString,"UTF-8"));
//buf.append(resultString);
//Toast.makeText(MainActivity.this, buf, Toast.LENGTH_SHORT).show();
URL url = new URL(buf.toString());
Log.e("check1","url_transformation works ok");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
Log.e("check2","open connection works ok");
conn.setRequestMethod("GET");
Log.e("check3","set get works ok");
if(conn.getResponseCode()==200){
Log.e("check4","get works");
Toast.makeText(MainActivity.this, "GET works", Toast.LENGTH_SHORT).show();
}
else
{
Log.e("check5","get fails");
Toast.makeText(MainActivity.this, "GET fails", Toast.LENGTH_SHORT).show();
}
}
catch(Exception e){
Toast.makeText(MainActivity.this, "other problems occur", Toast.LENGTH_SHORT).show();
}
03-05 20:47:19.486: W/System.err(16066): android.os.NetworkOnMainThreadException
03-05 20:47:19.486: W/System.err(16066): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1178)
03-05 20:47:19.486: W/System.err(16066): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
03-05 20:47:19.486: W/System.err(16066): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
03-05 20:47:19.486: W/System.err(16066): at libcore.io.IoBridge.connect(IoBridge.java:112)
03-05 20:47:19.486: W/System.err(16066): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
03-05 20:47:19.486: W/System.err(16066): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
03-05 20:47:19.486: W/System.err(16066): at java.net.Socket.connect(Socket.java:872)
03-05 20:47:19.486: W/System.err(16066): at libcore.net.http.HttpConnection.(HttpConnection.java:77)
I think the exception log is as described as above. So what's wrong here?
I have tried AsyncTask as some of you suggested.
The code is as belowed:
private class HttpGetTask extends AsyncTask<Void , Void, String> {
private String URL = "http://192.168.1.100:9080/" + "?" +"content1="+resultString;
//buf.append("content1="+URLEncoder.encode(resultString,"UTF-8"));
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
//Log.e("check", "succeed");
#Override
protected String doInBackground(Void... param) {
HttpGet request = new HttpGet(URL);
//Log.e("check1","succeed");
Log.e("url",URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
Log.e("check3","succeed");
return mClient.execute(request, responseHandler);
} catch (ClientProtocolException exception) {
exception.printStackTrace();
Log.e("check4","succeed");
} catch (IOException exception) {
exception.printStackTrace();
Log.e("check5","succeed");
}
Log.e("check6","succeed");//to this point
return null;
}
#Override
protected void onPostExecute(String result) {
if (null != mClient)
mClient.close();
//Log.e("check6","succeed");
mTextView.setText(result);
}
}
03-06 14:57:07.117: W/System.err(12451): org.apache.http.conn.ConnectTimeoutException: Connect to /192.168.1.100:9080 timed out
03-06 14:57:07.137: W/System.err(12451): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:121)
03-06 14:57:07.137: W/System.err(12451): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
the Log shows that there is an IOException in my codes and the value of mClient will eventually be null.I have looked online for the same situation and it seems this occurs when data takes too much time to respond that is requested. And many of the answers suggested I should reset Timeout and allow more time for the request to be sent. But I don't really understand where to put the reset codes in my situation. Can anyone help with this? Thanks.
NetworkOnMainThreadException is thrown when you try to perform network operations on the main/UI thread. This is not allowed in Android. Instead, you need to perform network operations in a background thread. You can do this using an AsyncTask.
You can put this on onCreate(), but the best option is to use AsyncTask.
StrictMode.ThreadPolicy threadPolicy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(threadPolicy);
private String urlPost = "http://192.168.1.66:8080/DataCollectionServlet/";
#Override
protected void doWakefulWork(Intent intent) {
// https://stackoverflow.com/q/14630255/281545
HttpURLConnection connection = null;
try {
connection = connection();
w("connection"); // allrigt
final OutputStream connOutStream = connection.getOutputStream();
w("GEToUTPUTsTREAM"); // I never see this
} catch (IOException e) {
e.printStackTrace(); // No route to host
} finally {
if (connection != null) connection.disconnect();
}
}
private HttpURLConnection connection() throws MalformedURLException,
IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(urlPost)
.openConnection();
// connection.setDoInput(true);
connection.setDoOutput(true); // triggers POST
// connection.setUseCaches(false); // needed ?
// TODO : http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
// connection.setRequestProperty("Connection", "Keep-Alive");
// connection.setRequestProperty("User-Agent",
// "Android Multipart HTTP Client 1.1"); // needed ?
return connection;
}
The server in 192.168.1.66:8080/DataCollectionServlet/ is up and running. My device IP is 192.168.1.65. I disabled both window's and the router's firewall to no avail.
EDIT - stack trace :
java.net.SocketException: No route to host
at org.apache.harmony.luni.platform.OSNetworkSystem.connect(Native Method)
at dalvik.system.BlockGuard$WrappedNetworkSystem.connect(BlockGuard.java:357)
at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:204)
at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:437)
at java.net.Socket.connect(Socket.java:983)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:75)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:322)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:285)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:267)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:205)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:614)
at gr.uoa.di.monitoring.android.services.NetworkService.doWakefulWork(NetworkService.java:51)
at com.commonsware.cwac.wakeful.WakefulIntentService.onHandleIntent(WakefulIntentService.java:94)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:59)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.os.HandlerThread.run(HandlerThread.java:60)
Comments : Again, the phone and PC are both connected to the same router wirelessly (same SSID)
Android 2.3.7 Eclair, HTC Nexus 1 - could it be a bug ?
EDIT 2013.11.13 : still interested in ana explanation of my answer
Well well - disabling the (WPA-PSK) Encryption on the router I connect alright. I would accept as an answer a (programmatic) work around
EDIT : entering the URL into the android device's browser I do see the doGet() page. I reenabled all firewalls - the only thing that makes a difference is toggling encryption on and off
I am trying to write a AndroidTestCase for one of my classes that make connection to a server and parse the returned JSONObject. When I test the functionality in the UI, the file works fine and the correct information are parsed and displayed. When I input the URL into my browser, I get the correct JSONObject back. However, when I try to get the JSONObject through a AndroidTestCase and simply verifying that it's not null, I get IOException when it tries to get the corresponding JSONObject for an url. I verified that the url it's using is correct. Here's the stack trace.
java.net.UnknownHostException: api.penncoursereview.com
at java.net.InetAddress.lookupHostByName(InetAddress.java:506)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
at java.net.InetAddress.getAllByName(InetAddress.java:256)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:69)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:322)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:285)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:267)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.retrieveResponse(HttpURLConnectionImpl.java:1018)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:512)
at edu.upenn.cis.cis350.backend.Parser.retrieveJSONObject(Parser.java:34)
at edu.upenn.cis.cis350.test.ParserTest.test_retrieveJSONObject(ParserTest.java:22)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at junit.framework.TestCase.runTest(TestCase.java:154)
at junit.framework.TestCase.runBare(TestCase.java:127)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:118)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1448)
Any idea why the code works in simulator but not in test?
Thanks in advance for the help!
edit:
Here is the relevant method:
public JSONObject retrieveJSONObject(String path){
try{
URL url = new URL(path);
Log.w("Parser: retrieveJSONObject", "url=" + url);
URLConnection connection = url.openConnection();
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Log.v("Length",builder.toString());
return new JSONObject(builder.toString());
}
catch(IOException e) {
Log.w("Parser: retrieveJSONObject", "IOException: Bad Url");
e.printStackTrace();
return null;
} catch (JSONException e) {
Log.w("Parser: retrieveJSONObject", "JSONException: mis-formatted JSON");
e.printStackTrace();
return null;
}
}
Line 34 is the line initializing the BufferedReader.
I guess what you are missing is the INTERNET permission.
Considering that your method is defined static in Utils class, the following test works.
public void testRetrieveJSONObjectWithUrl() {
final String url = "http://www.bom.gov.au/fwo/IDV60901/IDV60901.94868.json";
assertNotNull(Utils.retrieveJSONObject(url));
}
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.