Why can't I set header with Android HTTPURLConnection? - android

So I'm trying to connect to a REST server with HTTPURLConnection. The HTTPGET request needs to be of content-type application/json. When I use setRequestProperty("Content-Type", "application/json"); the value is overriden to "text/html" but when I use setRequestProperty("Accept", "application/json"); the Content-Type is set to application/json. Why can't I use Content-Type when specifying? Clarification is greatly appreciated.
My current guess is that "Accept" works with HTTPGET and "Content-Type" is for HTTPPOST.
More code:
connection.setRequestMethod("GET");
connection.setUseCaches(false);
//connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");

AFAIK, the Content-Type header in an HTTP request would be for the type of content being sent as the body, and is used on requests like POST and PUT. Accept is the header that indicates what MIME types the requester would like to receive in a response.

Related

httpUrlConnection not returning cached response when server returns HTTP_NOT_MODIFIED

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();

missing parameter when sending request to server with HttpURLConnection

I need to post schoolname=xyz&schoolid=1234 to server. I wrote the following Android client code:
String data = "schoolname=xyz&schoolid=1234";
//The url is correct
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Accept-Encoding", "gzip");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = new BufferedOutputStream(conn.getOutputStream());
os.write(data.toString().getBytes("UTF-8"));
//response complains that missing parameter 'schoolname'
int responseCode = conn.getResponseCode();
...
After I send my request with above code, server however constantly complains that schoolname parameter is missing. What do I miss or did wrong?
Have a look at [this example that explains How to use a HttpURLConnection to POST data
If you're planning on doing a lot of web communication, take a look at Square's Retrofit which will help you automate a lot of this work.
You can't use the format "key=value&key1=value1" for http post. That would work fine only for get. In this case you need something like this:
List<NameValuePair> nameValuePairs;
nameValuePairs.add(new BasicNameValuePair("schoolname", "xyz"));
nameValuePairs.add(new BasicNameValuePair("schoolid", "1234"));
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
httpPost.execute();
I figured out myself, the reason is that I forget to call flush() on output stream. After flush it, everything works fine.

Adding Authorization Header to HTTP POST request in android(Using JSON)

My authorization header is "Authorization: TRUEREST username=user &password=pass&apikey=key&class=class". How to put it into HTTPPOST request..?
I am doing it like :
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Authorization","TRUEREST");
httppost.setHeader("username","user");
httppost.setHeader("password","pass");
httppost.setHeader("apikey","key");
httppost.setHeader("class","class");
Credentials don't get send. What is wrong in this code??
Kindly help..!!
Thanks in advance.
First, are you sure you need to put all of those in the 'Authorization' header? Second what you are doing is adding 5 different headers with each value, not adding a single 'Authorization' header.
The '&' usually means you need to send those values as POST/GET parameters, but do check your specs.

android, how to send username and password to webservice as header fields?

i am trying to create an application on android phone that takes username and password from user, encrypt the password using md5 then connect to url with these parameters.
a code to connect worked fine on iphone, but i couldn't find something like it in android:
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:myURL];
[request setHTTPMethod:#"GET"];
[request addValue:usernameField.text forHTTPHeaderField:#"UserName"];
[request addValue:MD5Pass2 forHTTPHeaderField:#"Password"];
i tried to connect via httpurlconnection used post/get Dataoutputstream, httpclient send parameters httpget/httppost, but no success.
I think I need to send the parameters as headerfield but I don't know how.
note: I compared encryption results and it was correct.
I find the Apache library to be much more straightforward when it comes to HTTP.
An example of this would be as follows:
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://www.internet.com/api"));
Normally with a GET request you would use GET parameters, ie append them to the end of the URL like so:
String url = "http://www.internet.com/api?UserName=YourUsername&Password=yourpassword"
request.setURI(new URI(url));
But since you specified you want them as headers you could:
request.addHeader("UserName", username);
request.addHeader("Password", password);
and then:
HttpResponse response = client.execute(request);
//Parse the response from the input stream object inside the HttpResponse
you can try using HttpUrlConnection with this http://developer.android.com/reference/java/net/URLConnection.html#addRequestProperty%28java.lang.String,%20java.lang.String%29

Android and JSP: xml in http post request

I should send within an http post request (inside the request body) an xml string formatted like the following:
<message>
<man>
<age>18</age>
<sex>m</sex>
</man>
<result>
<math>8</math>
<science>8</science>
</result>
</message>
The POST requests should have a Content-Type header set to "text/xml; charset=UTF-8".
How can i do this? i din't get how httppost works for jsp...heeelp! :)
Answer to this should be this:
http://amitkgaur.blogspot.it/2009/12/post-xml-data-without-form-in-jsp-and.html

Categories

Resources