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.
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'm going to use HttpUrlConnection for calling a WebAPI. I simply call url.OpenConnectionMethod() to open the connection, but it doesn't work. Both allowUserInteraction and client.connected values of HtpUrlConnection instance are false.
URL url = new URL("http://myserver/service/api/ads/getads");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
any help would be appreciated.
Try this:
URL url = new URL("http://yourserver/x/y/z");
URLConnection urlConnection = url.openConnection();
if this doesn't work can I see any exceptions?
So I am currently writing an android app that will get tweets from a particular user, using Twitter's 1.1 Application-only-auth, which requires a POST HTTP request to get a bearer token. I have a method set up that uses an HttpsURLConnection to open a connection, but
conn.setDoOutput(true); method isn't working
conn.doOutput stays false
the request stays the default GET.
Am I doing something wrong?
This method is called in an AsyncTask's doInBackground() method:
public String getRequestBearerToken(String endUrl) throws IOException {
String encodedCred = encodeKeys("API-key", "API-secret");
HttpsURLConnection connection = null;
try {
URL url = new URL(endUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
// POST request properties
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", getResources()
.getString(R.string.app_name));
connection.setRequestProperty("Authorization", "Basic "
+ encodedCred);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Content-Length", "29");
connection.setUseCaches(false);
...
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);
HI,
I need to use http post method for web-service in android application .But in android shows error when use this method .How to use this method in application or any other equal method for replacing this http post method.
thanks,
Lakshmanan.
URL url = new URL(my_ip_address);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("METHOD", "POST");
HttpURLConnection httpConnection = (HttpURLConnection)connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
//do your stuff
}