I'm trying to check the status code error when I load a webview to check for any http errors.
Although when I try to check if my device can connect to the link https://www.google.pt/?gws_rd=ssl almost always gives the following error:
java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)
at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:545)
at libcore.io.IoBridge.recvfrom(IoBridge.java:509)
at java.net.PlainSocketImpl.read(PlainSocketImpl.java:489)
at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:241)
at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
at org.apache.http.impl.io.AbstractSessionInputBuffer.readLine(AbstractSessionInputBuffer.java:191)
at org.apache.http.impl.conn.DefaultResponseParser.parseHead(DefaultResponseParser.java:82)
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.createTunnelToTarget(DefaultRequestDirector.java:765)
at org.apache.http.impl.client.DefaultRequestDirector.establishRoute(DefaultRequestDirector.java:664)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:384)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:575)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:498)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:476)
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: libcore.io.ErrnoException: recvfrom failed: ECONNRESET (Connection reset by peer)
at libcore.io.Posix.recvfromBytes(Native Method)
at libcore.io.Posix.recvfrom(Posix.java:141)
at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:164)
at libcore.io.IoBridge.recvfrom(IoBridge.java:506)
... 26 more
I tried other links and sometimes it gives this error too, rarely it gives me http 200.
Here is how I'm doing the request:
class RetrieveConnectionStatus extends AsyncTask<String, Integer, Integer> {
private Integer mHttpStatus;
protected Integer doInBackground(String... urls) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(urls[0]);
HttpResponse httpResponse = httpClient.execute(httpRequest);
mHttpStatus = httpResponse.getStatusLine().getStatusCode();
// if( mHttpStatus != 200) {
} catch (Exception e) {
L.e(CampaignScreen.class, Log.getStackTraceString(e));
mHttpStatus = 404;
}
return mHttpStatus;
}
}
Update: I'm accessing via 3G and http pages also gives this error. Also via Wireless this works without a problem
Can someone help me on this? What is going on?
Related
so I have created two separate apps, one acts as a client & the other acts as a server. Both devices are connected using hotspot:
Connection between the devices is successful. For transferring data from the server to the client, I am using the below code:
public static String downloadDataFromSender(String apiUrl) throws IOException {
InputStream is = null;
try {
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
/* Starts the query */
conn.connect();
conn.getResponseCode();
is = conn.getInputStream();
/* Convert the InputStream into a string */
return readIt(is);
} finally {
if (is != null) {
is.close();
}
}
}
But I keep getting the following error:
java.net.SocketTimeoutException: connect timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:343)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:205)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:187)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
at java.net.Socket.connect(Socket.java:586)
at com.android.okhttp.internal.Platform.connectSocket(Platform.java:113)
at com.android.okhttp.Connection.connectSocket(Connection.java:196)
at com.android.okhttp.Connection.connect(Connection.java:172)
at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:367)
at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:130)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:329)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:126)
at com.wifiscanner.utils.DownloadUtils.downloadDataFromSender(DownloadUtils.java:27)
at com.wifiscanner.tasks.SenderAPITask.doInBackground(SenderAPITask.java:29)
at com.wifiscanner.tasks.SenderAPITask.doInBackground(SenderAPITask.java:14)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
The url I am using in the download is this:http://192.168.43.1:52287/files
The connection is successful as I said. So not sure why I am getting network is unreachable. This happens intermittently and not always.
Could someone provide some detail on why this is happening?
Details about my app:
compileSdkVersion 22
buildToolsVersion '22.0.1'
defaultConfig {
applicationId "My application id"
minSdkVersion 13
targetSdkVersion 22
versionCode 4
versionName "2"
}
I'm using HttpsURLConnection for Login authentication.But now i'm facing javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException that too on devices running below android lollipop.Authentication is working as expected on devices running OS verions abouve 5.Please let me know your suggestions for this issue.
Here is the code i'm using :
HttpsURLConnection conn = null;
try {
URL url = new URL("URL to my application");
String authStr = username + ":" + password;
String authEncoded = Base64.encodeToString(authStr.getBytes(), Base64.NO_WRAP);
conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Basic " + authEncoded);
conn.setDoOutput(true);
conn.setConnectTimeout(120000);
int code = conn.getResponseCode();
if(code ==200){
for(int i=0;i<conn.getHeaderFields().size();i++){
String value = conn.getHeaderField(i);
HeaderElement headerElement = BasicHeaderValueParser.parseHeaderElement(value, new BasicHeaderValueParser());
if(headerElement.getName().equals("SMSESSION")){
cookieString = SMSESSION+"="+headerElement.getValue();
Log.d("validhdvaluelogin",cookieString);
cookieeditor.putString(ArticleListActivity.CURRENT_COOKIE,
cookieString);
cookieeditor.apply();
return true;
}
}
}else {
return false;
}
}
catch (Exception e) {
e.printStackTrace();
return false;
}
if (conn != null) {
conn.disconnect();
}
return false;
And here is the exception :
javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL
handshake aborted: ssl=0xb87b0350: Failure in SSL library, usually a
protocol error
error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake
failure (external/openssl/ssl/s23_clnt.c:741 0xa9092990:0x00000000)
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:448)
at com.android.org.conscrypt.OpenSSLSocketImpl$SSLInputStream.<init>(OpenSSLSocketImpl.java:661)
at com.android.org.conscrypt.OpenSSLSocketImpl.getInputStream(OpenSSLSocketImpl.java:632)
at org.apache.http.impl.io.SocketInputBuffer.<init>(SocketInputBuffer.java:70)
at org.apache.http.impl.SocketHttpClientConnection.createSessionInputBuffer(SocketHttpClientConnection.java:83)
at org.apache.http.impl.conn.DefaultClientConnection.createSessionInputBuffer(DefaultClientConnection.java:170)
at org.apache.http.impl.SocketHttpClientConnection.bind(SocketHttpClientConnection.java:106)
at org.apache.http.impl.conn.DefaultClientConnection.openCompleted(DefaultClientConnection.java:129)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:172)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.ericsson.labs.it.infoservicemx.network.AuthComm.login(AuthComm.java:148)
at com.ericsson.labs.it.infoservicemx.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:312)
at com.ericsson.labs.it.infoservicemx.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:230)
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: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xb87b0350: Failure in SSL library, usually a protocol error
error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:741 0xa9092990:0x00000000)
at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:405)
... 23 more
I have finally found solution to my problem.
By using NetCipher library for httpsurlconnection.
Instead of using:
HttpsUrlConnection conn = (HttpsURLConnection) url.openConnection();
Use:
HttpsUrlConnection conn = NetCipher.getHttpsURLConnection(url);
This solved my SSLv3 handshake issue.
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.
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;
}
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!