private String urlPost = "http://192.168.1.66:8080/DataCollectionServlet/";
#Override
protected void doWakefulWork(Intent intent) {
// https://stackoverflow.com/q/14630255/281545
HttpURLConnection connection = null;
try {
connection = connection();
w("connection"); // allrigt
final OutputStream connOutStream = connection.getOutputStream();
w("GEToUTPUTsTREAM"); // I never see this
} catch (IOException e) {
e.printStackTrace(); // No route to host
} finally {
if (connection != null) connection.disconnect();
}
}
private HttpURLConnection connection() throws MalformedURLException,
IOException {
HttpURLConnection connection = (HttpURLConnection) new URL(urlPost)
.openConnection();
// connection.setDoInput(true);
connection.setDoOutput(true); // triggers POST
// connection.setUseCaches(false); // needed ?
// TODO : http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
// connection.setRequestProperty("Connection", "Keep-Alive");
// connection.setRequestProperty("User-Agent",
// "Android Multipart HTTP Client 1.1"); // needed ?
return connection;
}
The server in 192.168.1.66:8080/DataCollectionServlet/ is up and running. My device IP is 192.168.1.65. I disabled both window's and the router's firewall to no avail.
EDIT - stack trace :
java.net.SocketException: No route to host
at org.apache.harmony.luni.platform.OSNetworkSystem.connect(Native Method)
at dalvik.system.BlockGuard$WrappedNetworkSystem.connect(BlockGuard.java:357)
at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:204)
at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:437)
at java.net.Socket.connect(Socket.java:983)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:75)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:322)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:285)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:267)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:205)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:614)
at gr.uoa.di.monitoring.android.services.NetworkService.doWakefulWork(NetworkService.java:51)
at com.commonsware.cwac.wakeful.WakefulIntentService.onHandleIntent(WakefulIntentService.java:94)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:59)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.os.HandlerThread.run(HandlerThread.java:60)
Comments : Again, the phone and PC are both connected to the same router wirelessly (same SSID)
Android 2.3.7 Eclair, HTC Nexus 1 - could it be a bug ?
EDIT 2013.11.13 : still interested in ana explanation of my answer
Well well - disabling the (WPA-PSK) Encryption on the router I connect alright. I would accept as an answer a (programmatic) work around
EDIT : entering the URL into the android device's browser I do see the doGet() page. I reenabled all firewalls - the only thing that makes a difference is toggling encryption on and off
Related
My laptop and android device are on the same WIFI network. I have localhost on my laptop (XAMPP) and I want to test my app via real device (the emulator working fine with localhost).
I did some googling and found out that I need to pay special attention to the port. So, I changed my http conf from listen 80 to listen 8888. I tried to access localhost:8888 on my laptop browser and its working fine.
However, I keep getting this exception when trying to access http://my real IP address:8888/test/index.php on my android device :
java.net.SocketTimeoutException: failed to connect to /my real ip address (port 8888) after 30000ms
This is where the exception occured :
try{
URL url = new URL(getUrl);
//Logr.e("WebGetURL: "+getUrl);
urlConnection = (HttpURLConnection) url.openConnection();
if(isJson)
{
urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
urlConnection.setRequestProperty("Expect", "100-continue");
}
urlConnection.setRequestProperty("Cache-Control", "no-cache");
urlConnection.setConnectTimeout(30*1000);
urlConnection.setReadTimeout(timeout*1000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
//urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Linux; U; Android; en-us;) AppleWebKit/522+ (KHTML, like Gecko) Safari/419.3");
//urlConnection.addRequestProperty("http.agent", "Commons-HttpClient/3.1 ()");
for (Entry<String, List<String>> entry :
urlConnection.getRequestProperties().entrySet()) {
}
OutputStream in = new BufferedOutputStream(urlConnection.getOutputStream());
ret = convertStreamToStringOutputStream(urlConnection,in,postData);
//Logr.d("xx",ret);
} catch (Exception e) {
e.printStackTrace();
}finally {
//Logr.d("zz", "error, disconnected");
urlConnection.disconnect();
}
return ret;
Try using localhost or local network IP address rather than Global IP address(my IP address).
I'm using the following code for post requests
public String executeHttpPost(String uri, String data) {
HttpURLConnection conn = null;
URL url = null;
String s = null;
try {
url = new URL(uri);
conn = (HttpURLConnection) url.openConnection();
if (conn instanceof HttpsURLConnection) {
Log.d("HTTPS", "HttpsUrl");
}
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
DisplayResponseHeaders(conn);
s = readStream(conn.getInputStream());
Log.d("body", s);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
s = null;
e.printStackTrace();
} finally {
conn.disconnect();
}
return s;
}
When I use it over http, all works good , but over https I get
java.io.EOFException
at libcore.io.Streams.readAsciiLine(Streams.java:203)
at libcore.net.http.HttpEngine.readResponseHeaders(HttpEngine.java:573)
at libcore.net.http.HttpEngine.readResponse(HttpEngine.java:821)
at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:283)
libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
ru.fors.remsmed.fragment.NetHelper.executeHttpPost(NetHelper.java:234)
ru.fors.remsmed.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:424)
ru.fors.remsmed.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:1)
android.os.AsyncTask$2.call(AsyncTask.java:287)
java.util.concurrent.FutureTask.run(FutureTask.java:234)
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
java.lang.Thread.run(Thread.java:856)
threadid=14: thread exiting with uncaught exception (group=0x40a71930)
I found the issue about recycling connections bug in httpsurlconnection and possible solution :
if (Build.VERSION.SDK != null && Build.VERSION.SDK_INT > 13) {
conn.setRequestProperty("Connection", "close");
}
But it isn't work for me.
Try to change your code like this:
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded; charset: UTF-8");
byte[] output = data.getBytes("UTF-8");
conn.setFixedLengthStreamingMode(output.length);
os = conn.getOutputStream();
os.write(output);
os.flush();
os.close();
DisplayResponseHeaders(conn);
if (conn.getResponseCode() == 200) { // or other 2xx code like 204
s = readStream(conn.getInputStream());
Log.d("body", s);
}
else {
// handle error conditions like 404, 400, 500, ...
// now it may be necessary to read the error stream
InputStream errorStream = conn.getErrorStream();
// ...
}
AFAIK you should always close all streams you opened. I'm not sure whether conn.disconnect() is doing that for you.
If you want to code your HTTP(S) requests more conveniently, you can have a look at DavidWebb where you have a list of libraries helping you to avoid using cumbersome HttpURLConnection.
That EOFException suggests the response is malformed - perhaps lacking a blank line after the headers. Some HTTP client code is more forgiving in that case, for me iOS could handle my server responses fine but I was getting EOFException on Android using HttpURLConnection.
My server was using python SimpleHTTPServer and I was wrongly assuming all I needed to do to indicate success was the following:
self.send_response(200)
That sends the initial response header line, a server and a date header, but leaves the stream in the state where you are able to send additional headers too. HTTP requires an additional new line after headers to indicate they are finished. It appears if this new line isn't present when you attempt to get the result body InputStream or response code etc with HttpURLConnection then it throws the EOFException (which is actually reasonable, thinking about it). Some HTTP clients did accept the short response and reported the success result code which lead to me perhaps unfairly pointing the finger at HttpURLConnection.
I changed my server to do this instead:
self.send_response(200)
self.send_header("Content-Length", "0")
self.end_headers()
No more EOFException with that code. It's possible the "Connection: close" solutions trigger some behaviour on certain servers that might work around this (eg ensuring the response is valid before closing) but that wasn't the case with the python SimpleHTTPServer, and the root cause turned out to be my fault.
NB: There are some bugs on Android pre-Froyo (2.2) relating to keep-alive connections - see the blog post here: http://android-developers.blogspot.co.uk/2011/09/androids-http-clients.html. I'm yet to see convincing evidence of bugs with newer versions of Android.
I've been looking for help on the other questions, but can not find something, while in a review activity need internet connection, even with activated 3G but can not connect (have exceeded data use or firewall) tutorials or help I have found do not include that.
I use this little function to detect Public Wifi redirects to sign on page. If this function returns false, it means you could not connect to the intended page despite having your 3G or Wifi on. With this you can show the user any page, for example a "No Internet Connection" page.
public boolean networkSignOn() {
HttpURLConnection urlConnection = null;
try {
URL url = new URL("http://clients3.google.com/generate_204");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setInstanceFollowRedirects(false);
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
urlConnection.setUseCaches(false);
urlConnection.getInputStream();
return urlConnection.getResponseCode() == 204;
} catch (IOException e) {
Log.v("Walled garden check - probably not a portal: exception " + e, "");
return false;
} finally {
if (urlConnection != null) urlConnection.disconnect();
}
}
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!
I have a code to perform POST Requests with HttpsUrlConnection, the code works fine, but some of my Users have SIM Cards with a closed Usergroup and they need to set a proxy in the settings of their apn. If they set the proxy, i need to modify my code. I Tryed this:
HttpsURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String urlServer = "https://xxx";
String boundary = "*****";
try {
URL url = new URL(urlServer);
SocketAddress sa = new InetSocketAddress("[MY PROXY HOST]",[My PROXY PORT]);
Proxy mProxy = new Proxy(Proxy.Type.HTTP, sa);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;boundary=" + boundary);
//this is supposed to open the connection via proxy
//if i use url.openConnection() instead, the code works
connection = (HttpsURLConnection) url.openConnection(mProxy);
//the following line will fail
outputStream = new DataOutputStream(connection.getOutputStream());
// [...]
} catch (Exception ex) {
ret = ex.getMessage();
}
now i receive the error:
javax.net.ssl.SSLException: Connection closed by peer
If i use url.OpenConnection() wuithout Proxy and without Proxysettings in the apn, the code works, what might be the Problem?
You could try this alternative way of registering a proxy server:
Properties systemSettings=System.getProperties();
systemSettings.put("http.proxyHost", "your.proxy.host.here");
systemSettings.put("http.proxyPort", "8080"); // use actual proxy port
You can use the NetCipher library to get easy proxy setting and a modern TLS config when using Android's HttpsURLConnection. Call NetCipher.setProxy() to set the app-global proxy. NetCipher also configures the HttpsURLConnection instance to use the best supported TLS version, removes SSLv3 support, and configures the best suite of ciphers for that TLS version. First, add it to your build.gradle:
compile 'info.guardianproject.netcipher:netcipher:1.2'
Or you can download the netcipher-1.2.jar and include it directly in your app. Then instead of calling:
HttpURLConnection connection = (HttpURLConnection) sourceUrl.openConnection(mProxy);
Call this:
NetCipher.setProxy(mProxy);
HttpURLConnection connection = NetCipher.getHttpURLConnection(sourceUrl);