Android HttpUrlConnection Response wait time - java

I have below code. I am getting HTTP response code -1. Just to troubleshoot, I would like to know if I should wait after making connection for a while before checking the http response code.
String requestURL = "https://www.google.com";
HttpURLConnection connection = new HttpURLConnection;
connection = (HttpURLConnection) requestUrl.openConnection();
connection.setConnectTimeout(20000);
connection.setReadTimeout(20000);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.connect();
OutputStreamWriter writer = new OutputStreamWriter(this.connection.getOutputStream());
writer.write(getHttpData());
writer.flush();
writer.close();
if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new inputStreamReader(connection.getInputStream()));
}
Is getResponseCode() or getInputStream() blocking call ? Am I reading response too soon ? Should I wait ?
Thanks for the help.

One reason you could be getting the weird HTTP response code of -1 is the connection-pooling with-http-keep-alives bug that's in Android platform versions up to (and including) Froyo, ie Android v2.2.
The Android Developer Blog gives the following code snippet to resolve the problem (note that they say it doesn't include Froyo, although we found that it did - the snippet below is modified accordingly):
private void disableConnectionReuseIfNecessary() {
// HTTP connection reuse which was buggy pre-froyo
if (Integer.parseInt(Build.VERSION.SDK) <= Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}
}
Try calling that when your app starts-up and see if it fixes your problem.

Related

HTTPUrlConnection is returning 400 for Linux but works on Windows

I am making a request to twitch api with the following code
URL url = new URL("https://api.twitch.tv/kraken/streams/?channel=" + channelID)
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.addRequestProperty("Accept", "application/vnd.twitchtv.v5+json");
connection.addRequestProperty("Client-ID", clientID);
connection.setUseCaches(false);
connection.setDoInput(true);
InputStream inputStream = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder response = new StringBuilder();
while ((line = br.readLine()) != null) {
response.append(line);
response.append("\r");
}
br.close();
return response.toString();
This gets the correct response on windows, however when i run it on my Raspberry PI it gets a 400 response. I found a similar question on Stack Overflow i tried to set the proxy settings with this code
System.setProperty("java.net.useSystemProxies", "true");
However this failed to fix this request, any idea what is causing this?
Just incase anyone comes accross this problem in the future, i upgraded to java 11 and implemented it using http client in java 11 i have no idea at all why this fixes the issue but it does.

curl command line vs HttpURLConnection API service call response time differences

I am consuming a web services using HttpURLConnection which took 60 seconds to return the response but when I use CURL(command line) for same operation with same parameters then it took only 20 - 25 seconds to return the response.
what could be the issue in API service call through HttpURLConnection because it's taking longer time to return the response.
HttpURLConnection API call code :
`
url = new URL(this._serviceURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
connection.setRequestProperty("Accept", "application/xml;");
connection.setRequestProperty("SOAPAction", "http://www.xxtest.com/Request");
connection.setDoInput(true);
connection.setDoOutput(true);
// Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(xmlRequest);
wr.flush();
wr.close();
// Get Response
responseCode = connection.getResponseCode();
String xmlResponse = "";
if (responseCode == HttpURLConnection.HTTP_OK) { // success
is = connection.getInputStream();
xmlResponse = IOUtils.toString(is);
// Decode base64 and Decompress
final GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(Base64.decodeBase64(xmlResponse.getBytes())));
xmlResponse = IOUtils.toString(gzipInputStream);
}`
CURL command :
curl -XPOST -H "Content-type: text/xml" -H "SOAPAction: http://www.xxtest.com/Request" -H "Accept: application/xml;" -d #request_soap.xml 'http://www.xxtest.com/xmlservices.asmx' > response.xml
Update :
Above mentioned HttpURLConnection API call java code - when executed from a Web Application (Tomcat) then it's taking longer time(60 seconds) to return the response but when I run the same java code as standalone java program on same server then it is returning response in 20 seconds. Exactly same code. Now, I don't understand why the same code is taking longer time when it is getting executed from a Web Application.
The performance problem might be at this point
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(xmlRequest);
wr.close();
I would guess following will get better Performance.
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(xmlRequest);
out.close();
I have added Proxy.NO_PROXY in openConnection method in a HttpURLConnection API call code(mentioned in my question) and delayed response issue solved. The services which I was consuming were having proxy setting and because of that I was facing delayed response issue.
Please check below mentioned code snippet.
connection = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);

HTTP POST is not working from Java

I am trying to do an http post. Same code was working.But now it is not hitting my servlet now, but giving http response code 200. From browser same url is hitting the servlet. Is there anything that restricting my post?. Please help me on it. Sorry for bad english.
int timeout=3000;
String url="http://localhost:8020/WiCodeDynamic/WiCode?json=";
String requestUrl="{\"vspCredentials\":{\"id\":\"TET\",\"password\":\"test\"}}";
URL x = new URL(url);
HttpURLConnection connection =(HttpURLConnection)x.openConnection();
connection.setRequestMethod("POST");
//;charset=utf-8
connection.setRequestProperty("Content-type","application/json");
connection.setDoOutput(true);
connection.setConnectTimeout(timeout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
bw.write(requestUrl);
bw.flush();
int resp_code = connection.getResponseCode();
String resp_msg = connection.getResponseMessage();
System.out.println("resp_code="+resp_code);
System.out.println("resp_msg="+resp_msg);
brs,
Only a minor mistake. Move the json= from the end of your URL to the beginning of your POST request (requestUrl) and you should be fine.
Also I suggest you use URLEncoder.encode to escape the string you are transfering properly.

HttpURLConnection always return error 500

i'm trying to run a soap request in a basic http request...naturally i tried with external tools the message and is correct, like the endpoint i'm using as targetUrl, the wsdl is in something like
http://00.00.00.00/a-ws/services/basic?wsdl
and my actual end point is
http://00.00.00.00/a-ws/services/basic.targetservice
and i'm using this last as target url
URL url = new URL(targetUrl);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
connection.setRequestProperty("SOAPAction", action);
connection.setRequestProperty("User-Agent", "myagent");
connection.setRequestProperty("Host", "localhost");
//connection.setRequestProperty("Content-Length", "" + Integer.toString(message.getBytes().length));
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
OutputStream wr = connection.getOutputStream ();
wr.write (message.getBytes());
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line=null;
StringBuffer response = new StringBuffer();
while( (line = rd.readLine()) != null) {
if (line!=null)
response.append(line);
}
rd.close();
return response.toString();
the raw message is tested with chrome plugin, the only thing i can't test is headers but the result is always an exception on getInputStream
java.io.IOException: Server returned HTTP response code: 500 for URL:
why?
It was a very stupid issue of encoding (like I was supposing)...i didn't escape double quote inside the message.
The evidence of problem was visible using a fake http server that just echo contents.
UPDATE:
Another thing nobody already pointed out is that is useful in case of exception to retrieve
connection.getErrorStream()
that contains the response in case of error!

URLConnection sometimes returns empty string response?

I'm making an http GET request. It works in about 70% of my attempts. For some reason, I sometimes get no response string from a successful connection. I just setup a button in my app which keeps firing the code below. One call might fail to reply with a string, the next call works fine:
private onButtonClick() {
try {
doit();
} catch (Exception ex) {
...
}
}
public void doit() throws Exception {
URL url = new URL("http://www.example.com/service");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setAllowUserInteraction(false);
connection.setReadTimeout(30 * 1000);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Authorization",
"Basic " + Base64.encode("username" + ":" + "password"));
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder sb = new StringBuilder();
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
connection.disconnect();
// Every so often this prints an empty string!
System.out.println(sb.toString());
}
am I doing something wrong here? It seems like maybe I'm not closing the connection properly from the last call somehow and the response gets mangled or something? I am also calling doit() from multiple threads simultaneously, but I thought the contents of the method are thread-safe, same behavior though,
Thanks
Thanks
That method looks fine. It's reentrant, so calls shouldn't interfere with each other. It's probably a server issue, either deliberate throttling or just a bug.
EDIT: You can check the status code with getResponseCode.
For checking ResponseCode:
BufferedReader responseStream;
if (((HttpURLConnection) connection).getResponseCode() == 200) {
responseStream = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
} else {
responseStream = new BufferedReader(new InputStreamReader(((HttpURLConnection) connection).getErrorStream(), "UTF-8"));
}
For empty content resposneCode is 204. So if u can get empty body just add one more "if" with 204 code.
We also came across with the similar scenario, I came across the following solution for this issue:
- Setting up a user agent string on URLConnection object.
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 4.01; Windows NT)");
more details

Categories