I need to connect to server using SSL with REST. I am using HttpsURLConnection but somehow I cannot even get response code from server. The url is correct and when I try to get response code, it just throws nullPointerException.
Code snippet:
URL url = new URL("https", "xxx.com/yyy/zzz.svc", "myApi/test");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
Log.e("Response code", "Response from server: " + conn.getResponseCode());
What am I doing wrong here?
Note: I have to add remote server address and authorization token to header, but it have to return some response code anyway. For authorization error I have to receive error 400.
EDIT: The nullPointerException was hidden under Malformed URL.
Check out How to parse / read JSON data from the URL.
Related
I am trying to send XML data with POST request to the server. But getting 500 error.
URL url = new URL(AFConstants.ServerEndPoint);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type",
"application/xml;charset=utf-8");
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
DataOutputStream dataOutputStream = new DataOutputStream(http.getOutputStream());
String encoded = URLEncoder.encode(xml,"UTF-8");
dataOutputStream.writeBytes(encoded);
dataOutputStream.flush();
dataOutputStream.close();
Any ideas what is going wrong?
String xml contains this:
<?xml version=“1.0” encoding=“utf-8"?>
<AddSalesOrder revision=“8.0” environment=“Production” lang=“en-US” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=“C:\Data2\Ntp\shoprvparts\AddSalesOrder.xsd”>
<ApplicationArea>
...
</ApplicationArea>
<DataArea>
<Add confirm=“Always”/>
<SalesOrder>
<Header>
</Header>
<Line>
<LineNumber>1</LineNumber>
<OrderItem>
...
</OrderItem>
<OrderQuantity uom=“string”></OrderQuantity>
</Line>
</SalesOrder>
</DataArea>
</AddSalesOrder>
500 Internal Server Error or HTTP 500 - Internal Server Error
Cause of HTTP 500 Errors
Most of the time, "wrong" means an issue with the page or site's programming, but there's certainly a chance that the problem is on your end
so i think there will be error logs on the server and if you have access you can provide the server logs and will be easy to identify the problem
I am attempting to connect to my server using basic authentication, but when I set the Authorization header, it causes getInputStream to throw a fileNotFound exception.
Here is the relevant code:
URL url = new URL(myurl);
//set up the connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);//this is in milliseconds
conn.setConnectTimeout(15000);//this is in milliseconds
String authHeader = getAuthHeader(userID,pass);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setRequestProperty("authorization", authHeader);
//starts the query
conn.connect();
int response = conn.getResponseCode();
is = conn.getInputStream(); //throws the fileNotFound exception
Here is the thrown exception:
java.io.FileNotFoundException: http://<myIPaddress>/login/
Weirdly enough, I have found that the fileNotFound exception is only thrown if I try to set the request property to "authorization" or "Authorization" or any variation of that word. it is not thrown if I set it to "content-type" or "authosodifjsodfjs" (a random string), as here:
conn.setRequestProperty("content-type",authHeader)//no exception thrown
conn.setRequestProperty("authosodifjsodfjs",authHeader)//no exception thrown
If I don't set this header, I am able to connect to the server with this code and get the proper access-denied message that I am expecting.
I am also able to connect to the server and login properly if I use python's "requests" module, so it is not a problem with the server.
so my question is as follows:
1) what, if anything, am I doing wrong when setting the request property as "authorization"? how do I set the auth header properly?
2) if this is a bug with HttpURLConnection, how do I file a bug report?
Thank you.
edit: it was recommended to switch from:
conn.setRequestProperty("Authorization", authHeader);
to:
conn.addRequestProperty("Authorization", authHeader);
This did not fix the problem. It is still throwing the same exception.
EDIT:
still not sure why "Authorization" and "authorization" are causing fileNotFounExceptions, but using all caps seems to work properly. here is the shiny new working code:
conn.setRequestProperty("AUTHORIZATION",authHeader);
so it looks like it needs to be all caps. "HTTP_" will be automattically added to the front of this header, so the header that the server will see is "HTTP_AUTHORIZATION", which is what it should be.
Here is part of my OAuth code which sets Authorization header:
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setRequestProperty("User-Agent", "MyAgent");
httpUrlConnection.setConnectTimeout(30000);
httpUrlConnection.setReadTimeout(30000);
String baseAuthStr = APIKEY + ":" + APISECRET;
httpUrlConnection.addRequestProperty("Authorization", "Basic " + baseAuthStr);
httpUrlConnection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
httpUrlConnection.connect();
Why is the following code
URL url = new URL(urlStr);
Log.d(TAG, "Opening URL " + url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
String response = streamToString(urlConnection.getInputStream());
always giving me the following Exception at urlConnection.getInputStream()?
W/System.err(16253): java.io.FileNotFoundException: https://api.instagram.com/v1/media/search/access_token=1559619173.3c922fe.4fd71e26225a42a0a03fdd90ef8679a6?lat=48.858318956&lng=2.294427258&distance=500
W/System.err(16253): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
W/System.err(16253): at com.android.okhttp.internal.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:246)
W/System.err(16253): at br.com.dina.oauth.instagram.InstagramApp$5.run(InstagramApp.java:192)
You should remove urlConnection.setDoOutput(true); line because setDoOutput method force POST but instagram api work GET method.
You can also check this issue.
https://github.com/thiagolocatelli/android-instagram-oauth/issues/2
The code throwing the exception can be found for example in the okhttp github (Android uses that internally). The lines responsible are:
if (getResponseCode() >= HTTP_BAD_REQUEST) {
throw new FileNotFoundException(url.toString());
}
That simply means that the url you've provided did not result in a successful response. Throwing a *File*NotFoundException is behavior okhttp just copies from other implementations. Why someone chose this particular exception is beyond me.
If you simply put the url in the error message into a browser you'll see that you get a "Not found" page.
Explanation is simple: You're building the URL wrong. Instead of
search/access_token=...?lat=...
it needs to be
search?access_token=...&lat=...
access_token is a url parameter, not part of the path so it needs to get the ? as separator while lat becomes the second parameter which means ? needs to turn into &.
i'm trying to get the source code from a site using this code
conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(20000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.addRequestProperty("User-Agent", "Mozilla/5.0");
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
int response = conn.getResponseCode();
if (response = 307){
String locationHeader = conn.getHeaderField("Location");
URL redirectURL = new URL(locationHeader);
...
}
when the server responds with a 307 code i create a new connection with the same parameters as above with the new url given by the server.
this code works fine while following the first 2 redirects, at the third the server gives a relative url that forces a MalformedURLException when my code executes ' new URL(locationHeader); '.
so i tried to fix that adding the ' http://servername/ ' to the ' locationHeader ' string but doing that creates a loop cause the server then redirects to the first url of his redirection chain.
since my browser gets the source code from that server with no problems is there a way to achieve that with HttpURLConnection?
if someone is interested thanks to Fiddler i worked out a solution to this issue.
first i changed the "User-Agent" property to mimic the one of Mozilla then i manually tweaked the cookie the serer was sending in its reply with the relative path.
that did the trick. thank you Fiddler.
I have an api request which returns the response and also the response headers Last-Modified and Date.
I am using HttpUrlConnection for making the HTTP.GET requests. I am also using HttpResponseCache to cache the responses.
When the server returns a response code 200 ,the response is cached. I'm facing two issues now.
First : When the second time the api is requested, HttpUrlConnection sets the 'Date' header's value as the 'If-Modified-Since' header instead of using the 'Last-Modified' header's value.
I solved this issue by manually setting the If-Modified-Since header from the cached response. So now the server returns 304 the second time api is requested.
Here comes my second issue.
Second : Normally if the server returns 304 and the response is cached ,then HttpUrlConnection returns the cached response and the response code will be 200. This works as desired in the case of the api response which has ETag header in the response. But for the responses with only Last-Modified header , the HttpUrlConnection returns the response code as 304 itself and do not return the cached response.
Has any one encountered a similar issue ?
Please find below the java implementation for the api request.
URL url = new URL(this.url);
HttpURLConnection conn = getProtocolType(url);
conn.setRequestMethod("GET");
conn.setReadTimeout(timeOut);
conn.setConnectTimeout(timeOut);
conn.setInstanceFollowRedirects(true);
conn.setRequestProperty("User-Agent", this.userAgent);
conn.setRequestProperty("Cache-Control", "max-age=0");
conn.setUseCaches(true);
conn.setDefaultUseCaches(true);
conn.connect();
this.responseCode = conn.getResponseCode();