I am working on android app that should send GCS registration token to .NET MVC service that is running on localhost. I am using android Emulator with API 23 version. I have eliminated nearly everything that can be wrong, URL and parameters I send at the moment are hardcoded and If I copy paste url into browser (and replace 10.0.2.2 with localhost obviously) everything works. I am using fiddler but request that is supposed to originate from android does not get registered.
What I am getting instead is IO exception on InputStream inputStream = connection.getInputStream(); line
1-18 18:26:28.305 3488-3524/gcm.play.android.samples.com.gcmquickstart
W/System.err: java.io.FileNotFoundException:
http://10.0.2.2:61594/api/Account/RegisterDevice?token=2342342&coordinates=12.012;13.1515
01-18 18:26:28.305
3488-3524/gcm.play.android.samples.com.gcmquickstart W/System.err:
at
com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
01-18 18:26:28.305
3488-3524/gcm.play.android.samples.com.gcmquickstart W/System.err:
at
gcm.play.android.samples.com.gcmquickstart.RegistrationIntentService.sendRegistrationToServer(RegistrationIntentService.java:108)
01-18 18:26:28.305
3488-3524/gcm.play.android.samples.com.gcmquickstart W/System.err:
at
gcm.play.android.samples.com.gcmquickstart.RegistrationIntentService.onHandleIntent(RegistrationIntentService.java:69)
01-18 18:26:28.305
3488-3524/gcm.play.android.samples.com.gcmquickstart W/System.err:
at
android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:66)
01-18 18:26:28.306
3488-3524/gcm.play.android.samples.com.gcmquickstart W/System.err:
at android.os.Handler.dispatchMessage(Handler.java:102) 01-18
18:26:28.306 3488-3524/gcm.play.android.samples.com.gcmquickstart
W/System.err: at android.os.Looper.loop(Looper.java:148) 01-18
18:26:28.306 3488-3524/gcm.play.android.samples.com.gcmquickstart
W/System.err: at
android.os.HandlerThread.run(HandlerThread.java:61)
In watch connection.getResponseCode() status code is 400 (bad request) - but again server isn't even being hit.
I have configured following permissions in manifest:
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
Code that makes request:
StringBuffer chaine = new StringBuffer("");
try{
URL url = new URL("http://10.0.2.2:61594/api/Account/RegisterDevice?token=2342342&coordinates=12.012;13.1515");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("User-Agent", "");
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while ((line = rd.readLine()) != null) {
chaine.append(line);
}
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
Code from .NET Server
[AllowAnonymous]
[System.Web.Http.AcceptVerbs("GET", "POST")]
[System.Web.Http.HttpGet]
public void RegisterDevice(string token, string coordinates)
{
if (string.IsNullOrWhiteSpace(token))
{
throw new ArgumentNullException("Token is empty");
}
var data = new Data.EmergencyService();
if (data.AddUser(token, coordinates))
{
HttpContext.Current.Response.StatusCode = 200;
}
}
After I couldn't get fiddler to register request it made me to be completely lost.
Why can't I make request GET request from Andriod Studio which perfectly works in browser?
Ok for those who are wondering the reason for Android not being able to access PC localhost on http://10.0.2.2 was me running MVC service from Visual Studio in debug mode.
Once I have configured local IIS server and published website ( to local file system), Android was able to access it on http://10.0.2.2.
Hope this saves you some time.
Related
I have an android app which works perfectly on my phone (Huawei Mate 10 Pro) but when I try to run it on my tablet (Samsung Galaxy Tab S2) I get a java.io.FileNotFoundException when the app tries to access the input stream.
(I get the exception at "InputStream stream = connection.getInputStream();")
Is there a difference between Samsung and other devices regarding http communication? how can I write the code to work on every device?
Here's the code:
public String download_organisations(String url){
String jsonString = "";
try {
if(!url.startsWith("http://")){
url = "http://" + url;
}
if(url.endsWith("/")){
url = url.substring(0, url.lastIndexOf("/"));
}
url = url + ManagerSystemStatic.URL_SERVICE_WEB_ORGANISATION_MANAGER;
URL httpUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
connection.setConnectTimeout(10000);
InputStream stream = connection.getInputStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[1024];
while ((nRead = stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
byte[] inputStreamByteArray = buffer.toByteArray();
byte[] base64 = Base64.decode(inputStreamByteArray, 0);
byte[] decrypted = CipherUtils.decrypt(base64);
jsonString = new String(decrypted);
stream.close();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
Log.d("OrganisationManager", "Download succeded with response: " + connection.getResponseCode());
} else {
Log.d("OrganisationManager", "Download failed with response: " + connection.getResponseCode());
}
} catch (MalformedURLException e) {
Log.e("OrganisationManager", e.toString());
return DOWNLOAD_FAILED;
} catch (IOException e) {
Log.e("OrganisationManager", e.toString());
e.printStackTrace();
return DOWNLOAD_FAILED;
} catch (Exception e) {
Log.e("OrganisationManager", e.toString());
return DOWNLOAD_FAILED;
}
return jsonString;
}
Here's the StackTrace (with my url replaced):
E/OrganisationManager: java.io.FileNotFoundException: http://www.myurlhere.com
W/System.err: java.io.FileNotFoundException: http://www.myurlhere.com
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:254)
W/System.err: at com.organisationmanager.ble.common.WebPortalCommunicationHelper.download_organisations(WebPortalCommunicationHelper.java:210)
at com.organisationmanager.ble.ScanningActivity$UpdateOrganisations.doInBackground(ScanningActivity.java:414)
at com.organisationmanager.ble.ScanningActivity$UpdateOrganisations.doInBackground(ScanningActivity.java:403)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
D/InputTransport: Input channel constructed: fd=82
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
W/System.err: at java.lang.Thread.run(Thread.java:762)
When it starts the http communication I also get this in the debugger console:
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
Is that relevant?
After a lot of trial and error I still don't know what the issue was, but I tried using the class OkHttp instead of HttpUrlConnection, and suddenly everything worked. I have no idea why, but since I now have a working code I no longer need help with this issue. I hope this solution (changing class entirely) may help someone in the future. More about the class I used can be found here: http://square.github.io/okhttp/
I am trying to connect to a website to receive some JSON information. When I run the app in Android Studio using a connected Nexus 7 device I get a java.io.FileNotFound exception, but if I click on the name of the file that was not found, the response expected immediately shows in my browser. This is a new app for me, but I have done similar things in the past that have worked. I have been trying multiple things over the last 2 days and just can't seem to find the problem. Code blows up when I call connection.getInputStream(). All of this is running in an AsyncTask.
My Code
public byte[] getUrlBytes(String urlSpec) throws IOException{
URL url = new URL(urlSpec);
// urlSpec: https://api.weather.gov/points/48.0174,-115.2278
try {
connection = (HttpsURLConnection) url.openConnection();
} catch (IOException ioe) {
Log.d(TAG, "connection ioe: " + ioe.toString());
Toast.makeText(context, "#string/can_not_connect",
Toast.LENGTH_LONG).show();
}
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = connection.getInputStream(); *** Blows up here ****
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.d(TAG, "connection Response code: " +
connection.getResponseMessage());
}
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.close();
return out.toByteArray();
} finally {
connection.disconnect();
}
}
Logcat
04-02 15:40:59.693 32471-32495/com.drme.weathertest E/WeatherFetcher: Failed
to fetch items
java.io.FileNotFoundException: https://api.weather.gov/points/48.0174,-115.2278
*** Note that if I click on this file name, it works in my browser ***
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:206)
at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:25)
at com.drme.weatherNoaa.WeatherFetcher.getUrlBytes(WeatherFetcher.java:148)
at com.drme.weatherNoaa.WeatherFetcher.getUrlString(WeatherFetcher.java:183)
at com.drme.weatherNoaa.WeatherFetcher.downloadGridPoints(WeatherFetcher.java:202)
at com.drme.weatherNoaa.WeatherFetcher.requestForecast(WeatherFetcher.java:262)
at com.drme.weatherNoaa.WeatherFragment$SearchTask.doInBackground(WeatherFragment.java:329)
at com.drme.weatherNoaa.WeatherFragment$SearchTask.doInBackground(WeatherFragment.java:296)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
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:818)
Thanks for the help.
After additional reading of webservice documentation (some of it seems a little thin to me) and some additional posts on the web, the answer is that they require Acceptance and User-agent headers in the request. I have made these changes and the code now works as desired.
New static constants
private static final String ACCEPT_PROPERTY = "application/geo+json;version=1";
private static final String USER_AGENT_PROPERTY = "xxxx.com (xxxxxxxxx#gmail.com)";
Code changes
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestProperty("Accept", ACCEPT_PROPERTY); // added
connection.setRequestProperty("User-Agent", USER_AGENT_PROPERTY); // added
No other changes were required, although it took me awhile to figure out how to add the headers and what their format might be.
Thanks for checking this out.
I want to extend an existing Android app which sets up a http connection to a remote device which it sends commands to and receives values from.
The feature consists of a tunneled connection via a custom proxy server that has been set up. I have the http header format given which should make the proxy server create and provide a tunnel for my app.
CONNECT <some id>.<target ip>:80 HTTP/1.1
Host: <proxy ip>:443
Authorization: basic <base64 encoded auth string>
# Here beginns the payload for the target device. It could be whatever.
GET / HTTP/1.1
Host: 127.0.0.1:80
The app uses the Apache HttpClient library to handle it's connections, and I would like to integrate with that. This is not mandatory, however.
The authorization is standard conform basic auth.
I have trouble implementing this because it is not clear to me how the HttpClient is intended to be used for such behaviour.
There is no CONNECT method in the library, only GET, POST and so on. I figured this would then be managed by the proxy settings of the HttpClient instance.
The problem here is that the request line is not standard, since the CONNECT line contains an id which the custom proxy then would parse and interpret.
I now would like to know if there is any intended method to implement this using the Apache HttpClient and what it would look like with this sample data given, or if I have to implement my own method for this. And if so, which interface (there are a few that would sound reasonable to inherit from) it should implement.
Any explanation, snippet or pointer would be appreciated.
UPDATE:
I now have a small snippet set up, without Android. Just plain Java and Apache HttpClient. I still think the Host mismatch in the request is a problem, since I can't manage to establish a connection.
final HttpClient httpClient = new DefaultHttpClient();
// Set proxy
HttpHost proxy = new HttpHost (deviceId + "." + "proxy ip", 443, "https");
httpClient.getParams().setParameter (ConnRoutePNames.DEFAULT_PROXY, proxy);
final HttpGet httpGet = new HttpGet("http://" + "target device ip");
httpGet.addHeader ("Authorization", "Basic" +
Base64.encodeBase64String((username + ":" + password).getBytes()));
// Trying to overvrite the host in the header containing the device Id
httpGet.setHeader("Host", "proxy ip");
System.out.println("Sending request..");
try {
final HttpResponse httpResponse = httpClient.execute (httpGet);
final InputStream inputStream = httpResponse.getEntity ().getContent ();
final InputStreamReader inputStreamReader =
new InputStreamReader(inputStream, "ISO-8859-1");
final BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
final StringBuilder stringBuilder = new StringBuilder ();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine ()) != null) {
stringBuilder.append (bufferedStrChunk);
}
System.out.println("Received String: " + stringBuilder.toString());
}
catch (final ClientProtocolException exception) {
System.out.println("ClientProtocolException");
exception.printStackTrace();
}
catch (final IOException exception) {
System.out.println("IOException");
exception.
}
This looks fairly good to me in the way of "it could actually work".
Anyways, I receive the following log and trace:
Sending request..
2015/03/03 13:16:16:199 CET [DEBUG] ClientParamsStack - 'http.route.default-proxy': https://"device id"."proxy ip":443
2015/03/03 13:16:16:207 CET [DEBUG] SingleClientConnManager - Get connection for route HttpRoute[{}->https://"device id"."proxy ip":443->http://"target device ip"]
2015/03/03 13:16:16:549 CET [DEBUG] ClientParamsStack - 'http.tcp.nodelay': true
2015/03/03 13:16:16:549 CET [DEBUG] ClientParamsStack - 'http.socket.buffer-size': 8192
2015/03/03 13:16:16:563 CET [DEBUG] DefaultClientConnection - Connection shut down
2015/03/03 13:16:16:563 CET [DEBUG] SingleClientConnManager - Releasing connection org.apache.http.impl.conn.SingleClientConnManager$ConnAdapter#bc6a08
Exception in thread "main" java.lang.IllegalStateException: Unable to establish route.
planned = HttpRoute[{}->https://"device id"."proxy ip":443->http://"target device ip"]
current = HttpRoute[{s}->https://"device id"."proxy ip":443->http://"target device ip"]
at org.apache.http.impl.client.DefaultRequestDirector.establishRoute(DefaultRequestDirector.java:672)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:385)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
at run.main(run.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Any ideas what goes wrong?
UPDATE: As stated here, this might be due to a bug when redirecting. The fact that the target does redirect tells me, that I do not have reached the correct target, implying that the Host parameter may have not been overwritten.
In fact, this can't be done with the HttpClient at all, I tried at the wrong level. It works when done with a TcpSocket (or a SSLSocket). The custom CONNECT header can simply be assembled and sent like that:
final Socket tcpSocket = SSLSocketFactory.getDefault().createSocket("host ip", 443);
String connect = "custom CONNECT header";
tcpSocket.getOutputStream().write((connect).getBytes());
tcpSocket.getOutputStream().flush();
The response from the server can then be read with a BufferedReader or whatever.
This is where I got the socketIO files from.
https://github.com/Gottox/socket.io-java-client/tree/master/src/io/socket
I am on the client side.
I know connecting works when the server does not need authentication.
But when it needs authentication (Username and password), I get a handshaking error message.
How do I get passed authentication?? Could it be a server side error? Would the server side of things change if authentication was added?
This is the function that throws an error...I did not write it.
This line is the one causing problems: InputStream stream = connection.getInputStream();
It says it is caused by: java.io.FileNotFoundException: url:80/socket.io/1/
private void handshake() {
URL url;
String response;
URLConnection connection;
try {
setState(STATE_HANDSHAKE);
url = new URL(IOConnection.this.url.toString() + SOCKET_IO_1);
connection = url.openConnection();
if (connection instanceof HttpsURLConnection) {
((HttpsURLConnection) connection)
.setSSLSocketFactory(sslContext.getSocketFactory());
}
connection.setConnectTimeout(connectTimeout);
connection.setReadTimeout(connectTimeout);
/* Setting the request headers */
for (Entry<Object, Object> entry : headers.entrySet()) {
connection.setRequestProperty((String) entry.getKey(),
(String) entry.getValue());
}
InputStream stream = connection.getInputStream();
Scanner in = new Scanner(stream);
response = in.nextLine();
String[] data = response.split(":");
sessionId = data[0];
heartbeatTimeout = Long.parseLong(data[1]) * 1000;
closingTimeout = Long.parseLong(data[2]) * 1000;
protocols = Arrays.asList(data[3].split(","));
} catch (Exception e) {
error(new SocketIOException("Error while handshaking", e));
}
}
Problem solved (sort of), here: Android developpement, Gottox socket.io-java-client: file not fount Exception /socket.io/1/
(try using an earlier version of socket.io - by first deleting socket.io folder from node_modules and then install an older version, e.g., 0.9.16, using this command: npm install socket.io#0.9.16)
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!