java.net.UnknownHostException: Host is unresolved SOCKS proxy - android

I setup tor on a specific port and want to access the website through that port. The below code works perfectly in Android 7.0 but it gives below error in android 6.0. What may be the issue? The tor service successfully running at a specific port I am sending a request to.
Running sample code of this library (https://github.com/jehy/Tor-Onion-Proxy-Library)
Error
java.net.UnknownHostException: Host is unresolved: google.com
W/System.err: at java.net.Socket.connect(Socket.java:893)
W/System.err: at
cz.msebera.android.httpclient.conn.socket.PlainConnectionSocketFactory.connectSocket(PlainConnectionSocketFactory.java:74)
W/System.err: at
com.example.nandan.sampletorproxyapp.MyConnectionSocketFactory.connectSocket(MyConnectionSocketFactory.java:33)
W/System.err: at
cz.msebera.android.httpclient.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:134)
W/System.err: at
cz.msebera.android.httpclient.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
W/System.err: at
cz.msebera.android.httpclient.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
W/System.err: at
cz.msebera.android.httpclient.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
W/System.err: at
cz.msebera.android.httpclient.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
W/System.err: at
cz.msebera.android.httpclient.impl.execchain.RetryExec.execute(RetryExec.java:88)
W/System.err: at
cz.msebera.android.httpclient.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
W/System.err: at
cz.msebera.android.httpclient.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
W/System.err: at
cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
W/System.err: at
cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
W/System.err: at
com.example.nandan.sampletorproxyapp.MainActivity$TorTask.doInBackground(MainActivity.java:85)
W/System.err: at
com.example.nandan.sampletorproxyapp.MainActivity$TorTask.doInBackground(MainActivity.java:60)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:295)
W/System.err: at
java.util.concurrent.FutureTask.run(FutureTask.java:237) W/System.err:
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
W/System.err: at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
W/System.err: at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
W/System.err: at java.lang.Thread.run(Thread.java:818)
Main Activity
HttpClient httpClient = getNewHttpClient();
int port = onionProxyManager.getIPv4LocalHostSocksPort();
InetSocketAddress socksaddr = new InetSocketAddress("127.0.0.1", port);
HttpClientContext context = HttpClientContext.create();
context.setAttribute("socks.address", socksaddr);
HttpGet httpGet = new HttpGet("http://google.co.in");
HttpResponse httpResponse = httpClient.execute(httpGet, context); // GETTING ERROR HERE
static class FakeDnsResolver implements DnsResolver {
#Override
public InetAddress[] resolve(String host) throws UnknownHostException {
return new InetAddress[] { InetAddress.getByAddress(new byte[] { 1, 1, 1, 1 }) };
}
}
public HttpClient getNewHttpClient() {
Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", new MyConnectionSocketFactory())
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg,new FakeDnsResolver());
return HttpClients.custom()
.setConnectionManager(cm)
.build();
}
MyConnectionSocketFactory.java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import cz.msebera.android.httpclient.HttpHost;
import cz.msebera.android.httpclient.conn.socket.PlainConnectionSocketFactory;
import cz.msebera.android.httpclient.protocol.HttpContext;
public class MyConnectionSocketFactory extends PlainConnectionSocketFactory {
#Override
public Socket createSocket(final HttpContext context) {
InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("socks.address");
Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
return new Socket(proxy);
}
#Override
public Socket connectSocket(
int connectTimeout,
Socket socket,
final HttpHost host,
final InetSocketAddress remoteAddress,
final InetSocketAddress localAddress,
final HttpContext context) throws IOException{
InetSocketAddress unresolvedRemote = InetSocketAddress
.createUnresolved(host.getHostName(), remoteAddress.getPort());
return super.connectSocket(connectTimeout, socket, host, unresolvedRemote, localAddress, context);
}
}

Try changing
HttpGet httpGet = new HttpGet("http:google.co.in");
to
HttpGet httpGet = new HttpGet("http://google.co.in");
or
URI uri = new URIBuilder()
.setScheme("http")
.setHost("google.co.in")
.build();
HttpGet httpGet = new HttpGet(uri);
updated - try this
HttpHost target = new HttpHost("google.co.in", 80, "http");
HttpGet httpGet = new HttpGet("/");
HttpResponse httpResponse = httpClient.execute(target, httpGet, context);
If it don't work im not too sure. Maybe try this link hopefully this helps How to use HttpClientBuilder with Http proxy?

Related

AsyncTask - java.net.SocketException: Connection reset

I have an AsyncTask to fetch JSON data from a DB on my server. It works well normally but is failing sometimes with the below error. It seems like this happens when I keep the app idle but open for some time and then make a request.
doInBackground Method
try {
URL url = new URL(url_get_initial_posts);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data_string_language = URLEncoder.encode("selected_language","UTF-8")+"="+URLEncoder.encode(arg_language,"UTF-8")
+"&"+URLEncoder.encode("app_time","UTF-8")+"="+URLEncoder.encode(String.valueOf(arg_app_time),"UTF-8");
bufferedWriter.write(data_string_language);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_INITIAL_POST = bufferedReader.readLine()) != null) {
stringBuilder.append(JSON_INITIAL_POST + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
This line in the error
W/System.err: at com.indiparent.android.indiparent.PostTab$BackgroundJSONPosts.doInBackground(PostTab.java:343)
links to
InputStream inputStream = httpURLConnection.getInputStream();
Error
W/System.err: java.net.SocketException: Connection reset
W/System.err: at java.net.SocketInputStream.read(SocketInputStream.java:209)
W/System.err: at java.net.SocketInputStream.read(SocketInputStream.java:139)
W/System.err: at com.android.okhttp.okio.Okio$2.read(Okio.java:136)
W/System.err: at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:211)
W/System.err: at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:306)
W/System.err: at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:300)
W/System.err: at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:196)
W/System.err: at com.android.okhttp.internal.http.Http1xStream.readResponse(Http1xStream.java:186)
W/System.err: at com.android.okhttp.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:127)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:737)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:609)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:471)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:244)
W/System.err: at com.indiparent.android.indiparent.PostTab$BackgroundJSONPosts.doInBackground(PostTab.java:343)
W/System.err: at com.indiparent.android.indiparent.PostTab$BackgroundJSONPosts.doInBackground(PostTab.java:308)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:333)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
W/System.err: at java.lang.Thread.run(Thread.java:764)
Extra Info - This is not the only Asynctask in the application. There are more in other activities and fragments. For example - if AsynckTask of Activity 2 throws this error then if I come back to Activity 1 then its AsyncTask also does not work.
Am I supposed to do something here or on the server side? Appreciate any help here.

HTTP-request throws an exception FileNotFound

I have url: http://xxx.xxx.xxx.xxx:yyyy/api/Account/Register (ip:port). And in the browser I can get it like POST method without any problems. But Android throws an exception:
W/System.err: java.io.FileNotFoundException:
http://xxx.xxx.xxx.xxx:yyyy/api/Account/Register W/System.err: at
com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
W/System.err: at
com.contedevel.reserves.utils.RestApi.signUp(RestApi.java:37)
W/System.err: at
com.contedevel.reserves.activity.RegisterActivity$UserRegistrationTask.doInBackground(RegisterActivity.java:415)
W/System.err: at
com.contedevel.reserves.activity.RegisterActivity$UserRegistrationTask.doInBackground(RegisterActivity.java:396)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288)
W/System.err: at
java.util.concurrent.FutureTask.run(FutureTask.java:237) W/System.err:
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err: at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err: at
java.util.concurrent.ThreadPoolExecutor$Wo9191rker.run(ThreadPoolExecutor.java:587)
W/System.err: at java.lang.Thread.run(Thread.java:841)
A request method is POST 100%.
I create a new connection so:
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
Write arguments so:
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
final String body = builder.toString();
writer.write(body);
writer.flush();
writer.close();
os.close();
What could be the problem?

Android Failure in SSL library when connecting to my local XAMPP hosted website

I am new to any networking related programming, so I know I am diving in deep, but I have problems of getting a successful SSL-Handshake between my android HttpsURLConnection and my local XAMPP hosted website, well rather just a php script that returns Hello World! Let me first say that I can load this page from my computer(host) and from my android phone's browser (https).
The problem:
When I try to connect application with my server through an HttpsURLConnection I get the following error:
System.err﹕ javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x5e522ba8: Failure in SSL library, usually a protocol error
System.err﹕ error:1407743E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert inappropriate fallback (external/openssl/ssl/s23_clnt.c:744 0x5e5967e8:0x00000000)
System.err﹕ at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:449)
System.err﹕ at com.android.okhttp.Connection.upgradeToTls(Connection.java:146)
System.err﹕ at com.android.okhttp.Connection.connect(Connection.java:107)
System.err﹕ at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:294)
System.err﹕ at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
System.err﹕ at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
System.err﹕ at com.android.okhttp.internal.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:161)
System.err﹕ at yellowgames.battlenetfriendfinder.ServerConnection$TaskExecuter.doInBackground(ServerConnection.java:118)
System.err﹕ at yellowgames.battlenetfriendfinder.ServerConnection$TaskExecuter.doInBackground(ServerConnection.java:94)
System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:288)
System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
System.err﹕ at java.lang.Thread.run(Thread.java:841)
System.err﹕ Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x5e522ba8: Failure in SSL library, usually a protocol error
System.err﹕ error:1407743E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert inappropriate fallback (external/openssl/ssl/s23_clnt.c:744 0x5e5967e8:0x00000000)
System.err﹕ at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
System.err﹕ at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:406)
System.err﹕ ... 16 more
My Code:
My code is based on this: https://developer.android.com/training/articles/security-ssl.html
//Get Cert
try {
InputStream CertInputStream = a_sContext.getResources().openRawResource(R.raw.server);
//Read Cert
CertificateFactory CertFactory = CertificateFactory.getInstance("X.509");
Certificate Cert = CertFactory.generateCertificate(CertInputStream);
String Result = "Ca=" + ((X509Certificate) Cert).getSubjectDN();
Log.d("test", Result); //This Returns correct Cert information
//Create a keystore
KeyStore MyKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
MyKeyStore.load(null, null);
MyKeyStore.setCertificateEntry("ca", Cert);
//Create a TrustManager
TrustManagerFactory TMF = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
TMF.init(MyKeyStore);
//Create a SSLContext
m_pSSLContext = SSLContext.getInstance("TLS");
m_pSSLContext.init(null, TMF.getTrustManagers(), null);
HttpsURLConnection.setDefaultSSLSocketFactory(m_pSSLContext.getSocketFactory());
//Try and connect to the website
URL MyURL = new URL(m_sSecureHttp + m_sWebsite + m_sTestPath);
con = (HttpsURLConnection) MyURL.openConnection();
con.connect();
Result = new String();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));;
while((Line = reader.readLine())!= null) {
Result += Line;
}
}
catch (Exception e) { e.printStackTrace(); }
Server Side:
I generated a Certificate following: http://robsnotebook.com/xampp-ssl-encrypt-passwords
This seems to have worked since my local computer and the android browser can access it. Also, in XAMPP's ssl_request.log I can see all my connection attempts from my local computer or through my android browser, yet it doesn't even once mention a request from my application. This is the same for access.log.
I am testing the android application on Android 4.4.2
My actual question
Does anyone know how I can fix the SSL handshake error? Any tips are useful! I tried a lot of things I could find on google, but none worked so far.
There is a known bug on version Android 4.4.2 that is caused when accessing HTTPS using TLSv1.x protocol. Handshake fails because TLS is not supported so HttpsURLConnection falls back to SSLv3 protocol causing the error to happen on handshake. I haven't find a work around that doesn't involve reimplementing the HttpsURLConnection's TrustManagers to prevent the error or connecting insecurely.
This is what I did:
Feed a Custom trust manager to the your SSLContext:
// Trust manager that recognizes you acceptance criteria, that being ignoring handshake errors
ResourceTrustManager trustManager = new ResourceTrustManager(sslKeyStores);
TrustManager[] trustManagers = {trustManager};
// use: org.apache.http.conn.ssl.AllowAllHostnameVerifier, this can be optional depending on your case.
AllowAllHostnameVerifier resourceHostNameVerifier = new AllowAllHostnameVerifier();
// Install the trust manager and host name verifier
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustManagers, new java.security.SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(resourceHostNameVerifier);
} catch (Exception e) {
Log.e(TAG, "Invalid algorithm used while setting trust store:" +e.getMessage());
throw e;
}
To implement your trust manager just overwrite:
public void checkClientTrusted
public void checkServerTrusted
Mine uses local keystores to try to authorize the cert:
public class ResourceTrustManager implements X509TrustManager {
private static final String TAG = ResourceTrustManager.class.getName();
protected ArrayList<X509TrustManager> x509TrustManagers = new ArrayList<X509TrustManager>();
public ResourceTrustManager(Collection<KeyStore> additionalkeyStores) {
final List<TrustManagerFactory> factories = new ArrayList<TrustManagerFactory>();
try {
/**
* Consolidates central and aditional keystore to be used as trust managers
*/
final TrustManagerFactory original = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
original.init((KeyStore) null);
factories.add(original);
if(additionalkeyStores != null ) {
for (KeyStore keyStore : additionalkeyStores) {
final TrustManagerFactory additionalCerts = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
additionalCerts.init(keyStore);
factories.add(additionalCerts);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
for (TrustManagerFactory tmf : factories) {
for (TrustManager tm : tmf.getTrustManagers()) {
if (tm instanceof X509TrustManager) {
x509TrustManagers.add((X509TrustManager) tm);
}
}
}
ResourceAssert.hasLength(x509TrustManagers, "Could not initialize with no trust managers");
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// The default Trustmanager with default keystore
final X509TrustManager defaultX509TrustManager = x509TrustManagers.get(0);
defaultX509TrustManager.checkClientTrusted(chain, authType);
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
for( X509TrustManager tm : x509TrustManagers ) {
try {
tm.checkServerTrusted(chain,authType);
return;
} catch( CertificateException e ) {
StringBuilder issuers = new StringBuilder();
if(chain != null){
for(X509Certificate cert :chain){
issuers.append( " " +cert.getIssuerDN().getName() );
}
}
Log.e(TAG, "Untrusted host, connection is not secure "+ issuers + "\n\n" + e.getMessage());
}
}
}
public X509Certificate[] getAcceptedIssuers() {
final ArrayList<X509Certificate> list = new ArrayList<X509Certificate>();
for( X509TrustManager tm : x509TrustManagers ) {
list.addAll(Arrays.asList(tm.getAcceptedIssuers()));
}
return list.toArray(new X509Certificate[list.size()]);
}
}
This is not elegant at all, but gets the job done.

Connection reset by peer - Android request

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?

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;
}

Categories

Resources