I read many posts about setConnectTimeout but I really wonder how this method could work because we cannot initialize it before openConnection() exists.
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(2000);
...
So what is the purpose of setConnectTimeout()?
You're just opening / initializing the connection. You haven't actually called urlConnection.connect() yet. You're only initializing things like the URL, headers, setting your request method, etc.
It'll come into effect once you actually run the connection.
Related
I am developing an app in android studio and for web service calls I use HttpURLConnection. Although the class always uses GET when I call it, even tough I set it to POST. I have even double sat it to POST to make sure that's the method it will use.
URL url = new URL(Activity.this.getString(R.string.ws));
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestMethod("POST");
urlConn.setDoOutput(true);
urlConn.addRequestProperty("Content-Type", "application/json");
urlConn.addRequestProperty("Cache-Control", "no-cache");
urlConn.addRequestProperty("Accept", "application/json");
urlConn.addRequestProperty("Authorization", "Bearer " + fileHelper.getPropertyFromSharedPreferences(getString(R.string.key_token)));
urlConn.connect();
Anyone else has had this problem before? And how to fix it?
PS. I have also tried OKHTTP, but still the same problem
EDIT:
I have found out the reason that the method will always be GET, is because when I call setDoOutput it doesn't change the value, not even if I do
urlConn.setDoOutput(!urlConn.getDoOutput);
Do not use urlConn.connect();. Use urlConn.getOutputStream() instead.
I wrote a code to establish an HttpsUrlConnection and setRequestMethod as PUT. While debugging I see the method as GET. My SetRequestMethod is not working. I don't know why HttpsUrlConnection method in default GET.
My code looks like this
DisbleSSL disble = new DisbleSSL();
disble.disableSSLVerification();
URL url = new URL(url_string);
httpsUrlConnection = (HttpsURLConnection) url.openConnection();
httpsUrlConnection.setDoOutput(true);
httpsUrlConnection.setRequestMethod("PUT");
httpsUrlConnection.connect();
HttpsUrlConnection definitely support setrequestMethod.Actually but it may be Wrong Labled in Debugg console.
enter image description here
HttpsURLConnection use internal objects ->
protected DelegateHttpsURLConnection delegate
Try setRequestMethod before setDoOutput
I am getting java.lang.IllegalStateException:
java.lang.IllegalStateException: Cannot set request property after connection is made error when setRequestProperty method is called after
url.openConnection();
Here is what i am trying:
URL url = new URL("https://49.205.102.182:7070/obsplatform/api/v1/mediadevices/545b801ce37e69cc");
urlConnection = (HttpsURLConnection) url
.openConnection();
urlConnection.setRequestProperty("Content-Type","application/json");
any suggestions please? Thanks in advance.
This usually happens if you have in the debug watchers calls, such as conn.getResponseCode() or anything that queries the request result before the request was actually issued or completed.
This causes, that during debug, a request is performed by the watcher, before having properly set you request, and then it becomes invalid.
I only have this issue while in debugging mode,
Run without debugging (You can print logs) everything should work fine
The obvious thing is to think that you need to add properties before calling open on the URL. this however is not the case. i have seen many samples of settings being set AFTER url has been open (as counter intuitive as that is).
the problem in my case is that i had conn.getResponseCode() added in my watch list. removed that and all good.
... tricky.
please check below code
HttpURLConnection httpcon = (HttpURLConnection) ((new URL("a url").openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();
I was getting the same exception on setRequestProperty("Range","byte=" + downloadedSize + "-") .
After adding connection.setChunkedStreamingMode(0); the issue disappeared
I'm having the same issue.
I was observing this issue on Nexus 5. Code of my app constantly fails with the same exception (or its twin brother "cannot set request method ..")
What I've observed that it happens if i leave phone for a while. One it starts failing it fails all the time - but if i restart phone/emulator it's ok once again).
My suspicion is its either some bug in connection pooling on framework side, or somewhere in code resources are leaked.
i found the problem it's about ordering the code, if you are trying to add header and post parameters both, it's important to be careful about this
HttpURLConnection connection = (HttpURLConnection) urlConnection;
//// Add Request Headers
for (NameValuePair nvp :
request[0].getHeaderParams()) {
connection.setRequestProperty(nvp.getName(),nvp.getValue());
}
// done
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
//// Add Post Parameters
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
List<NameValuePair> params = new ArrayList<>(request[0].getPostParams());
bufferedWriter.write(getQuery(params));
// done
connection.setConnectTimeout(3000);
connection.setReadTimeout(3000);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.flush();
outputStream.close();
connection.connect();
in here, i have added header parameters then set setDoInput and setDoOutput then setRequestMethod and finally you can add POST parameters.
i don't know what is wrong with setRequestMethod but i think its preparing the connection by opening it or something and that's why it throws exception
not invoke setRequestProperty after write byte to OutputStream.
OutputStream os = connection.getOutputStream();
os.write("k=v".getBytes());
os.close();
you should invoke setRequestProperty above the code
To avoid the error:
java.lang.IllegalStateException: Cannot set request property after connection is made
We have to check the connection response before access the request header fields :
URL url = new URL("https://49.205.102.182:7070/obsplatform/api/v1/mediadevices/545b801ce37e69cc");
urlConnection = (HttpsURLConnection) url
.openConnection();
//Check connection
if(urlConnection.getResponseCode() == 200/*Successful*/) {
urlConnection.setRequestProperty("Content-Type","application/json");
...
...
}
I'm developing this android application which basically uploads images to a webservice.
I have a asynctask where I send the file to the server, using this code:
protected Boolean doInBackground(byte[]... params) {
HttpURLConnection connection = getConnection();
BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());
Log.d("OutputStream", "stream created, about to write");
out.write(params[0]);
Log.d("OutputStream", "all bytes written");
out.close();
}
Of course, this block of code is wrapped within a try catch, catching IOExceptions etc.
The problem is that when I interrupt the connection after I see the first logtext, an exception is never thrown or only after a really long time (talking about 20 minutes or so), which doesn't make any sense at all.
The HttpURLConnection is set up like this:
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", this.contentType);
urlConnection.setRequestProperty("User-Agent", String.format("custom-user-agent/%d", R.integer.version_code));
urlConnection.addRequestProperty("SessionID", this.sessionID);
urlConnection.setDoOutput(true);
urlConnection.setConnectTimeout(30000);
urlConnection.setReadTimeout(30000);
urlConnection.setChunkedStreamingMode(0);
urlConnection.setUseCaches(false);
urlConnection.connect();
Funny thing is, this only happens when interrupting a EDGE/3G connection. When I interrupt a wifi connection, the exception is thrown immediately (which, of course, is a lot more convenient).
Any idea on this?
A while ago, we've encountered this problem also, but only on a Samsung Galaxy SII with Android 2.3.4. All other devices did not have this issue. There is no way to program around this issue.
You don't need use urlConnection.connect(): the connection is open implicity when yo do the .getOutputStream().
Also, if you make the .connect(), you can't make it before at the .getOutputStream().
In addition, you must set the Content-Type header:
urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
I've encountered a rather strange error. I've written an android application that uploads an simple text file to a server. The code for the connection is as follows:
try {
URL = new URL(myURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+"---");
DataOutputStream output = new DataOutPutstream(connection.getOutputStream());
output.writeBytes(<my post request>);
output.flush();
output.close();
connection.connect();
}
When I run this method, the post request is never sent over to the server. Nothing shows up on wireshark and if I look in logcat, there are no errors and the connection gets made fine, the POST message is just never sent. However, if I add a simple line right after the connection.connect() such as:
connection.getResponseCode();
Suddenly the POST message gets sent over no problem. What's going on here? Am I required to get a response code in order for the message to get sent over?
Why do you have to call URLConnection#getInputStream to be able to write out to URLConnection#getOutputStream?
In short you must call getInputStream() and close it. getResponseCode() is also working because it requires an established connection.
You do not need to call
connection.connect();
which is redundant.
You can get working sample from here: http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
You set doInput to true. Maybe the url connection waits for an input because of that. Try to set it to false. But I could also be wrong. It is just a guess.