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);
Related
I have ASP.Net MVC4 WEB API, hosted in local IIS.
I request the api from android using GET method. Response is 405 Action not Allowed.
I Have This Method in Controller :
public IEnumerable<Table> GET()
{
return _repository.GetAll();
}
But When I Change the Method to POST:
public IEnumerable<Table> POST()
{
return _repository.GetAll();
}
and request from android with POST method.
I got the RESULTS.
I request both GET and POST with the same route.
'/api/tables'
In android project, I use HttpUrlConnection to request API.
try{
URL url = new URL(urls[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(5000 /* milliseconds */);
conn.setConnectTimeout(7500 /* milliseconds */);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestMethod(method);
conn.setDoInput(true);
if(method == "POST")
conn.setDoOutput(true);
if(params != null){
// Get OutputStream for the connection and
// write the parameter query string to it
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getURLEncodedString(params));
writer.flush();
writer.close();
}
// Starts the query
conn.connect();
What am i doing wrong?
info:
when request from browser Get Method return results and Post Method 405.
The problem is in my android project
Android Developer: HttpUrlConnection
HttpURLConnection uses the GET method by default. It will use POST if
setDoOutput(true) has been called.
stackoverflow: https://stackoverflow.com/questions/8187188/android-4-0-ics-turning-httpurlconnection-get-requests-into-post-requests
May be it's a routing issue. Make some little changes in your WebApi.config of webapi
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
One more important thing here is that with this style of routing, you must use attributes to specify the allowed HTTP methods (like [HttpGet]).
I have a server address that I want to connect my app to.
This is his address: "http://54.148.194.246:8080/".
I try to connect to it by this code:
clientSocket = new Socket("http://54.148.194.246/", 8080);
But my app gives me this error :
java.net.UnknownHostException: Unable to resolve host "http://54.148.194.246/": No address associated with hostname.
I added Internet permission and my wireless is on (those were the answers that I saw for this problem).
Any ideas?
Thanks.
You need to remove http://from the IP/hostname when passing it to the Socket constructor:
clientSocket = new Socket("54.148.194.246", 8080);
Alternatively, use the URL class for sending HTTP requests specifically:
URL url = new URL("http://54.148.194.246:8080/");
InputStream strm = (InputStream) url.getContent();
// use strm as needed...
Or:
URL url = new URL("http://54.148.194.246:8080/");
URLConnection conn = url.openConnection();
// use conn as needed...
URL url = new URL(URL path);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setDoInput(true);
connection.setUseCaches(true);
connection.connect();
InputStream is = connection.getInputStream();
Above code is my code of Android.
I try to connect an URL path and get information to InputStream is.
I try to connect the same URL path with the same wifi by Android phone and iPhone.
Android phone spend about 10 seconds by moto phones or HTC phones.
But iPhone only spend less than 3 seconds.
I think it may not only cause by wifi speed.(Because I try with the same wifi).
So I want to ask that is it possible improved by code?
Try using the apache HttpClient instead of URL.openConnection()
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet("http://your.url");
HttpResponse response;
try {
response = httpClient.execute(get);
InputStream is = response.getEntity().getContent();
} catch(Exception e){
e.printStackTrace();
}
Edit:
In API level 22 (Android M) the Apache HttpClient will be removed, so this approach is deprecated.
For more infor see :
http://developer.android.com/preview/behavior-changes.html#behavior-apache-http-client
The recommended approach is to use HttpUrlConnection (http://developer.android.com/reference/java/net/HttpURLConnection.html):
URL url = new URL("http://your.url");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
Use volley it is an HTTP library that makes networking for Android apps easier and faster. Volley is available on GitHub. Volley may be able to help you streamline and improve the performance of your app's network operations.
I connect to two servers (PROD is https, test server is http) on my applicaitons.
on J2ME: I can connect to this two servers without a problem.
on Android I can't connect to test-server. When connection is http, if I dont use setChunkedStreamingMode, I cant get responseCode(StringIndexOutOfBoundsException); if I use setChunkedStreamingMode, response code is 401. What should I do, where is my fault??
Here is my android code, Also if you want to see J2me code, I can add it, too.
URL url = new URL(getUrl());
URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setConnectTimeout(10000);
httpConn.setRequestProperty("User-Agent", util.getDeviceFullModel()
+ " " + util.getSoftwareVersion());
httpConn.setRequestProperty("Accept-Charset", "utf-8");
httpConn.setRequestProperty("Content-Type",
"text/xml; charset=utf-8");
httpConn.setRequestProperty("SOAPAction",
"http://tempuri.org/IAuthenticationServiceForGroup/"+conTypeString);
httpConn.setRequestProperty("Software-Version", AppData.VERSION);
httpConn.setChunkedStreamingMode(getParams().getBytes("UTF8").length);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
httpConn.connect();
os = httpConn.getOutputStream();
os.write(getParams().getBytes("UTF8"));
try {
os.close();
} catch (Exception e) {
onError(e);
}
response=httpConn.getResponseCode();
J2ME code:
HttpConnection c = (HttpConnection)XConnection.openConnection(XConnection.SERVER + "AuthenticationServiceForGroup.svc");
c.setRequestProperty("User-Agent", XUtil.getDeviceFullModel() + " " + XUtil.getSoftwareVersion());
c.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
c.setRequestProperty("SOAPAction", "http://tempuri.org/IAuthenticationServiceForGroup/"+conType);
c.setRequestProperty("Software-Version", XApp.VERSION);
c.setRequestMethod(HttpConnection.POST);
OutputStream os = null;
os = c.openOutputStream();
os.write(sParams.getBytes());
try {os.close();} catch (Exception e) {}
if (c.getResponseCode() == HttpConnection.HTTP_OK)
If you're using pre-2.3 devices, HTTPUrlConnection has known issues
http://android-developers.blogspot.com/2011/09/androids-http-clients.html
I solved this problem. I use ip adress instead of link. Server was Sharepoint server so, It tries to connect to directly sharepoint server, so server wants Authentication:) Dont use directly ip:)
The method disconnect from HttpURLConnection seems not to work properly.
If I execute the following code:
url = new URL("http:// ...");
connection = (HttpURLConnection) url.openConnection ();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
// Some code
connection.disconnect();
connection.setDoInput(false); // -> IllegalStateException
I get an IllegalStateException when I call the method setDoInput. The exception says:
Already connected
It sounds like you're trying to reuse the connection? i.e. altering the request properties after you've disconnected from the server, ready to make another connection.
If that is the case, then just create a new HttpURLConnection object.