Hi i have to send a get request to an url
http://onemoredemo.appspot.com/group?authToken=access_token&authMethod=oauth
with request body contains json object as shown below.
{"goupid":"some_variable"
}
Here is a section of java code for sending get request:
URL url1=new URL("http://onemoredemo.appspot.com/group?authToken="+access_token+"&authMethod=oauth");
conn=(HttpURLConnection) url1.openConnection();
conn.addRequestProperty("Content-type", "application/x-www-form-urlencoded");
conn.setRequestMethod("GET");
conn.setDoOutput(true);
JSONObject jj=new JSONObject();
HttpGet get;
get.
jj.put("groupid", "testing#iritesh.com");
conn.addRequestProperty("Content-TYpe", "application/json");
conn.getOutputStream().write(jj.toString().getBytes());
conn.connect();
InputStream is=conn.getInputStream();
I am getting an error java.io.FileNotFoundException.
I sent a request from mozilla browser to url
http://onemoredemo.appspot.com/group?authToken=ya29.AHES6ZRDl-RqiA8W0PhybU_hMluHrHRjlJBvq06Vze0izJq0Ovjc088&authMethod=oauth
It was giving me correct response but now its more than one hour so acccesstoken expire. I know its weird to send parameter as well as requestbody in get request but i have to send it.
Please help in how to send a json object in request body in get request.
Don't do it.
Read this:
http://tech.groups.yahoo.com/group/rest-discuss/message/9962
"Yes. In other words, any HTTP request message is allowed to contain a
message body, and thus must parse messages with that in mind. Server
semantics for GET, however, are restricted such that a body, if any,
has no semantic meaning to the request. The requirements on parsing
are separate from the requirements on method semantics.
So, yes, you can send a body with GET, and no, it is never useful to
do so.
This is part of the layered design of HTTP/1.1 that will become clear
again once the spec is partitioned (work in progress)."
For other interesting discussions on this check this:
https://stackoverflow.com/a/978094/550967
https://stackoverflow.com/a/978173/550967
https://stackoverflow.com/a/978519/550967
The body of a GET request is not read.
Have you tried adding it to the params:
http://onemoredemo.appspot.com/group?authToken=access_token&authMethod=oauth&goupid=some_variable
Related
I am trying to scrape a URL using Java. Basically I reproduce everything that was sent using browser including all the headers and POST requests, referrer etc. Note that the POST request is unique for my request that it is not influenced by a login. So, a simple copy and paste from Firefox's Tamper Data's given POST request has proved useful for such kind of replication.
con.setRequestMethod("POST");
con.setRequestProperty("Host", "www.example.com");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty(/*OTHER HEADERS ALSO*/);
urlParameters = "...";
con.setDoOutput(true);
int responseCode = con.getResponseCode();
Now, the above image is that from Tamper Data (My browsers data) showing the 1st response code is 302 and then there is another request whose response code is 200. But, responseCode in my code always shows a 500 (should be 302). Is there something wrong that I am doing? The POST data(forms the urlParameters variable in the given code) is as follows (This was totally copied from Tamper Data and is unique for my request as same in other browsers also):-
__EVENTTARGET=&__EVENTARGUMENT=&__LASTFOCUS=&__VIEWSTATE=%2FwEPDwULLTEyMDE3MzgzNDUPZBYCAgMPZBYKAgEPEA8WBh4ORGF0YVZhbHVlRmllbGQFB1Nlc3Npb24eDURhdGFUZXh0RmllbGQFB1Nlc3Npb24eC18hRGF0YUJvdW5kZ2QQFQIACTIwMTUtMjAxNhUCAAkyMDE1LTIwMTYUKwMCZ2dkZAIDDxAPFgYfAAUHQ1N0cmVhbR8BBQdDU3RyZWFtHwJnZBAVAgAEQkNPTRUCAARCQ09NFCsDAmdnZGQCBQ8QDxYGHwAFBHllYXIfAQUEeWVhch8CZ2QQFQQAATEBMgEzFQQAATEBMgEzFCsDBGdnZ2cWAQIBZAIHDxAPFgYfAAUIU2VtZXN0ZXIfAQUIU2VtZXN0ZXIfAmdkEBUCAAdTZW0gLSBJFQIAB1NlbSAtIEkUKwMCZ2dkZAILDw9kFgIeB29uY2xpY2sFEXJldHVybiB2YWxpZGF0ZSgpZGR%2BP3WXZxkNSdwV329YkiOBBIA2DLMC6gJWNx4dA3oG5Q%3D%3D&__VIEWSTATEGENERATOR=18D1343D&__EVENTVALIDATION=%2FwEdAA2G%2FZz3h1Fxl4xXSSABzk8Pb%2BUXWva1oWT3WqhNzatWVhEoIdYgal8I9hPfCoT1Itb7%2F7%2FyZSxxhcd9q9F7xksY%2FSdZeiYB08giIx9FAbkawOhcMS1yLyZ52cUQpBBi9r5shpYmVHzGls1H3mvqZEXw%2BZkl20IpE0Nr6jkkTdSbTjxJdi%2BkoPCwQLNr0uqw0NPQS5HQgTWcg263rJ2nwCO5DBdXef%2BTfjQcyvts5G%2Bbf%2FsH0gjLf9q4vWrLQV0SZzu1qAVHBnj%2FrF82mykk7zwRtJ8FryYi9kZUwYQMnOtqn2%2B7o7zN0ZhgzU6s38KDRXw%3D&ddlSession=123456&ddlStream=xxx&ddlYear=xx&ddlSemester=xxx&txtRoll=987654&btnViewAttendance=xxxx
After a lot of time wasted googling for the possible reasons for a 'Bad Request' when requesting for a token at https://accounts.google.com/o/oauth2/token, I decided to ask why this code can't obtain nothing but a 'bad request' response from the server...
String url = "https://accounts.google.com/o/oauth2/token";
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setChunkedStreamingMode(0);
con.setRequestMethod("POST");
con.setRequestProperty("Host", "accounts.google.com");
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
con.setRequestProperty("code", authCode);
con.setRequestProperty("client_id",
"[CLIENT_ID]");
con.setRequestProperty("client_secret", "[CLIENT_SECRET");
con.setRequestProperty("redirect_uri",
"http://localhost:8080/login");
con.setRequestProperty("grant_type", "authorization_code");
// Send post request
con.setDoOutput(true);
I did have to set con.setChunkedStreamingMode(0) because the server was returning an error related to content length.
Any ideas?
Could it be necessary to put the payload in a single line? how?
I believe the reason for the HTTP 400 (Bad Request) is you are sending code, client_id, client_secret, grant_type, and redirect_uri as HTTP request headers where you need to be sending them as query parameters in the body of the HTTP POST request (according to the Google OAuth2InstalledApp docs).
Take a look at Using java.net.URLConnection to fire and handle HTTP requests for a good example of how to send the HTTP POST. You'll need to take code, client_id, etc. and write them as a query string in the body:
// partial example only: only code and client_id are included
String query = String.format("code=%s&client_id=%s", code, client_id);
OutputStream out = con.getOutputStream();
out.write(query.getBytes("UTF-8"));
From the Google OAuth2 documentation, a sample HTTP POST request might look something like this:
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=4/v6xr77ewYqhvHSyW6UJ1w7jKwAzu&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code
I use HTTPUrlConnection to request a REST API.
I ser "Content-type" header as follows :
urlConnection.setRequestProperty("Content-type",
"application/x-www-form-urlencoded");
I set HTTP body as follows :
out = urlConnection.getOutputStream();
out.write(postParameters.getBytes("UTF-8"));
I don't know if I need to escape post parameters(which is a String) when I set HTTP header and body as shown above.
I just need Yes or No as answer, but would be great if the answer explains why yes or why no.
Since the data you are POSTing is to be interpreted as application/x-www-form-urlencoded, then it must have the form:
name1=value1&name2=value2&...
Therefore, the "value" parts MUST be URL-encoded, otherwise they will not be interpreted correctly.
Using POST with x-www-form-urlencoded is just moving the query-string part of the URL out of the request and into the body.
I'm trying to connect and post to a simple java webservice, running the post's URL from chrome succeeded, but android code skip the following lines (without throwing errors), but the webservice doesn't accept the post
HttpPost post = new HttpPost(setFacebookEventsAddress+userId+"/"+accesstoken);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
HttpResponse response = client.execute(post);
the webservice method signature handling the above request:
#GET
#Path("setData/{user_id}/{accessToken}")
#Produces(MediaType.APPLICATION_JSON+ ";charset=utf-8")
public String setData(#PathParam("user_id") String user_id,
#PathParam("accessToken") String accessToken) {
since I manage to post throw my browser, anyone can help with what's wrong with my android code?
URL url = new URL(setFacebookEventsAddress+userId+"/"+accesstoken);
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
ja = readStream(con.getInputStream());
Using HttpURLConnection instead of HttpPost did the trick for me, thanks for all the helpers!
It is not possible to say with any certainty (given the evidence), but my guess would be that the expression
setFacebookEventsAddress + userId + "/" + accesstoken
is evaluating to a different URL to the one you are using from the web browser.
I suggest that you try the following:
Turn on request logging on your server, and compare the URLs in the requests being sent.
Modify your client to print out the response status code and the response body. The latter is likely to be an error page that will give you more clues.
Another possible problem is that your code doesn't appear to be sending any body with the POST request.
On revisiting this, the problem was that you were using / trying to do a POST to a web service that you had configured to support GET only. I expect that if you had looked at the status code you would have found that the response code was "Method not supported".
I want to send a GET requests that accept only results of type application/rdf+xml using the Accept: header. Is the following code right?
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept", "application/rdf+xml");
InputStream response = connection.getInputStream();
#gigadot nailed it, the Accept header is a suggestion to the server which the server is free to ignore.
If your application can only accept RDF/XML then you need to add logic to the receipt of the request to enforce this.
You can use the getContentType() method of a URLConnection to see what content type the server returned you and take an appropriate action (e.g. report an error) if it does not match your requirements.