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;
}
Related
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?
I have the following code, which i use to check the second level of internet connectivity to a particular server.
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 8443));
DefaultHttpClient client = new DefaultHttpClient();
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, Constants.HTTP_CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParameters, Constants.HTTP_CONNECTION_TIMEOUT);
HttpGet httpget = new HttpGet(Utility.getCloudUrl());
try {
HttpResponse response = httpClient.execute(httpget);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = new String();
while ((l = in.readLine()) !=null){
sb.append(l);
}
in.close();
String data = sb.toString();
if (data.length() > 0){
synchronized (lock) {
isInternetAvialbale = true;
}
listener.onInternetReachable();
}else{
synchronized (lock) {
isInternetAvialbale = false;
}
listener.onInternetNotReachable();
}
} catch (IOException e) {
synchronized (lock) {
isInternetAvialbale = false;
}
listener.onInternetNotReachable();
return;
}
Everything works fine on a Wifi network. But when this code executes on a 3g network, I get the following exception:
java.lang.IllegalStateException: Scheme 'http' not registered.
at org.apache.http.conn.scheme.SchemeRegistry.getScheme(SchemeRegistry.java:80)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:126)
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:670)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at com.day.demo.DayApplication$3.run(DayApplication.java:340)
at java.lang.Thread.run(Thread.java:841)
I did search through a few similar questions but was not able to understand.
Could someone please help me with this?
If you are connected to the internet using an organization's WiFi, make sure you can access the internet (and not just connect to it). If the WiFi access requires a sign in, please sign in and then proceed with the HTTP/HTTPS requests.
I got a very annoying problem now with my android development. I have a list which loading a bunch of content, each is an xml file with different address. Which means I need to sends bunch of http get request to server.
The problem if the request is less than roughly 180 times, I mean continues, very fast http request, the app just works fine. When the amount reach around 180, the connection to internet of the whole device will be lost. That means not only the app won't work, even the default browser or other apps which require internet will also not work.
This will recover after 1 minutes or two. But during this time there are no internet connection.
I do have set permissions in mifest file.
Here is my code for http connection:
public class HTTPService {
private static String response;
public HTTPService() {
response = null;
}
public static String httpGet(String requestURL) {
//Reset response's value to null
response = null;
//DEBUG LOG
Log.i("HTTPService", "Start GET request with URL " + requestURL);
//this function will do http getting action and response checking at same time.
//and assign proper information into the response string.
executeRequest(new HttpGet(requestURL));
Log.i("HTTPService", "GET request return with: " + response);
return response;
}
public static String httpPost(String requestURL, String postString) throws Exception {
//Assemble POST request
HttpPost request = new HttpPost(requestURL);
StringEntity input = new StringEntity(postString);
input.setContentType(CommonCodes.CONTENT_TYPE);
request.setEntity(input);
//DEBUG LOG
Log.i("HTTPService", "Start POST request with URL" + requestURL + ", and post content " + postString);
executeRequest(request);
return response;
}
public static void httpPut(String requestURL, String postString) throws Exception {
//Assemble PUT request
HttpPut request = new HttpPut(requestURL);
StringEntity input = new StringEntity(postString);
input.setContentType(CommonCodes.CONTENT_TYPE);
request.setEntity(input);
//DEBUG LOG
Log.i("HTTPService", "Start PUT request with URL" + requestURL + ", and put content " + postString);
executeRequest(request);
}
public static String httpDelete(String requestURL) {
HttpDelete request = new HttpDelete(requestURL);
//DEBUG LOG
Log.i("HTTPService", "Start DELETE request with URL" + requestURL);
executeRequest(request);
return response;
}
public static void executeRequest(HttpUriRequest request) {
//Check Internet Connection
if (!CheckInternetConnection.checkInternetConnection()) {
responseValidation(CommonCodes.NO_CONNECTION, 0);
}
HttpClient client = sslHttpClient();
HttpResponse httpResponse;
try {
//*********PLACE WHERE ERROR HAPPENS IN ERROR LOG!******//
httpResponse = client.execute(request);
//Check if the request success. If it success, should return 200 as status code.
if (httpResponse.getStatusLine().getStatusCode() != CommonCodes.HTTP_SUCCESS) {
//DEBUG LOG
Log.i("HTTPService", "Request failed with HTTP status code" + httpResponse.getStatusLine().getStatusCode());
//Go through checker
responseValidation(null, httpResponse.getStatusLine().getStatusCode());
}
//When request succeed, retrieve data.
//HttpEntity entity = httpResponse.getEntity();
//Convert stream data into String.
if (!httpResponse.getEntity().equals(null)) {
InputStream instream = httpResponse.getEntity().getContent();
//Convert InputStream to String.
response = convertStreamToString(instream).trim();
//Close stream
instream.close();
httpResponse.getEntity().consumeContent();
}
//Go through checker
responseValidation(response, httpResponse.getStatusLine().getStatusCode());
client.getConnectionManager().shutdown();
} catch (ClientProtocolException e) {
Log.e("HTTPService: ", "HTTP Request With ClientProtocolException Detected");
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
Log.e("HTTPService: ", "HTTP Request With IOException Detected");
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
public static void responseValidation (String response, int statusCode)
{
//Is this a HTTP Error?
if (statusCode != CommonCodes.HTTP_SUCCESS) {
response = CommonCodes.HTTP_FAIL;
}
//Is the response contains nothing?
else if (response.equals(null) || response.equals("")) {
response = CommonCodes.RESPONSE_EMPTY;
}
//Is there an internet connection?
else if (response.equals(CommonCodes.NO_CONNECTION)){
response = CommonCodes.NO_CONNECTION;
}
}
public static HttpClient sslHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new SSLSocket(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 8080));
registry.register(new Scheme("https", sf, 8443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(
params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
The error message I got when the connection lost is this:
05-06 12:13:57.697 28670-28767/com.lai.android E/HTTPService:﹕ HTTP Request With IOException Detected
05-06 12:13:57.697 28670-28767/com.lai.android W/System.err﹕ org.apache.http.conn.HttpHostConnectException: Connection to http://test.myworkspace.com:8080 refused
05-06 12:13:57.697 28670-28767/com.lai.android W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
05-06 12:13:57.697 28670-28767/com.lai.android W/System.err﹕ at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-06 12:13:57.697 28670-28767/com.lai.android W/System.err﹕ at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-06 12:13:57.697 28670-28767/com.lai.android W/System.err﹕ at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-06 12:13:57.697 28670-28767/com.lai.android W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-06 12:13:57.697 28670-28767/com.lai.android W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-06 12:13:57.697 28670-28767/com.lai.android W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-06 12:13:57.697 28670-28767/com.lai.android W/System.err﹕ at com.lai.android.services.http.HTTPService.executeRequest(HTTPService.java:138)
05-06 12:13:57.697 28670-28767/com.lai.android W/System.err﹕ at com.lai.android.services.http.HTTPService.httpGet(HTTPService.java:73)
05-06 12:13:57.697 28670-28767/com.lai.android W/System.err﹕ at com.lai.android.modules.watchlistgroup.WatchListActivity.getSingleVehicle(WatchListActivity.java:238)
05-06 12:13:57.697 28670-28767/com.lai.android W/System.err﹕ at com.lai.android.modules.watchlistgroup.WatchListActivity$InitWatchListActivity.doInBackground(WatchListActivity.java:144)
05-06 12:13:57.705 28670-28767/com.lai.android W/System.err﹕ at com.lai.android.modules.watchlistgroup.WatchListActivity$InitWatchListActivity.doInBackground(WatchListActivity.java:109)
05-06 12:13:57.705 28670-28767/com.lai.android W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
05-06 12:13:57.705 28670-28767/com.lai.android W/System.err﹕ at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
05-06 12:13:57.705 28670-28767/com.lai.android W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:137)
05-06 12:13:57.705 28670-28767/com.lai.android W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
05-06 12:13:57.705 28670-28767/com.lai.android W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
05-06 12:13:57.705 28670-28767/com.lai.android W/System.err﹕ at java.lang.Thread.run(Thread.java:856)
05-06 12:13:57.705 28670-28767/com.lai.android W/System.err﹕ Caused by: java.net.ConnectException: failed to connect to /192.168.48.95 (port 8080): connect failed: ENETUNREACH (Network is unreachable)
05-06 12:13:57.705 28670-28767/com.lai.android W/System.err﹕ at libcore.io.IoBridge.connect(IoBridge.java:114)
05-06 12:13:57.713 28670-28767/com.lai.android W/System.err﹕ at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
05-06 12:13:57.713 28670-28767/com.lai.android W/System.err﹕ at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
05-06 12:13:57.713 28670-28767/com.lai.android W/System.err﹕ at java.net.Socket.connect(Socket.java:842)
05-06 12:13:57.713 28670-28767/com.lai.android W/System.err﹕ at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
05-06 12:13:57.713 28670-28767/com.lai.android W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
05-06 12:13:57.713 28670-28767/com.lai.android W/System.err﹕ ... 17 more
05-06 12:13:57.713 28670-28767/com.lai.android W/System.err﹕ Caused by: libcore.io.ErrnoException: connect failed: ENETUNREACH (Network is unreachable)
05-06 12:13:57.713 28670-28767/com.lai.android W/System.err﹕ at libcore.io.Posix.connect(Native Method)
05-06 12:13:57.713 28670-28767/com.lai.android W/System.err﹕ at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
05-06 12:13:57.713 28670-28767/com.lai.android W/System.err﹕ at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
05-06 12:13:57.713 28670-28767/com.lai.android W/System.err﹕ at libcore.io.IoBridge.connect(IoBridge.java:112)
05-06 12:13:57.721 28670-28767/com.lai.android W/System.err﹕ ... 22 more
Any advice will be welcome! I'm thinking if this is caused by running up of ports. But I don't know how to solve it. Thank you!
Lucky....I solved it.
The problem is I have too many HTTP Clients instance, which used up all ports on the Phone.
Android have a max connection limit, and it takes time to release the ports which are been used. So if the requests are heavy and happens in very short time, the device just won't got enough time to release them.
The solution is instead of using new client every time, use only one client for all request.
Adding this to the code:
private static HttpClient client;
public static synchronized void createHttpClient() {
if(client == null) {
Log.i("HTTPService", "Create Client");
client = sslHttpClient();
}
}
Then call this constructor from beginning of the application.
Then replace everywhere where create new http client with the static client.
Problem solved, I will go for a beer.
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 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!