Bad Request 400 when requesting Google OAuth2 token, Java - java

I've gotten an auth code from doing a "GET" request and signing in, and I'm trying to use that code to get an auth token using an http "POST", but I always get response code 400. My code is as follows:
// Create HTTP Objects
HttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("https://www.googleapis.com/oauth2/v4/token");
// Add Header
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
// Create Parameters
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("code", code));
params.add(new BasicNameValuePair("client_id", client_id));
params.add(new BasicNameValuePair("client_secret", client_secret));
params.add(new BasicNameValuePair("redirect_uri", redirect_uri));
params.add(new BasicNameValuePair("grant_type", "authorization_code"));
// Add Parameters and Excecute
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpclient.execute(httpPost);
It seems to match perfectly the documentation they provide here:
https://developers.google.com/identity/protocols/OAuth2WebServer
Any ideas why this is happening?

Alright, I figured it out, it was as simple as it took long enough to debug my code for the auth code from Google to expire.
I got a new code from Google and it worked.

Related

The wordpress api POST request in order to create a post through java returns 403 forbidden only for specific post

The wordpress API returns 403 forbidden for specific post whereas for other posts works fine
Tried to change the authCookie but it did not work.
LOG.info("Creating post with title:" + title);
String nonce = getNonceForCreatePost(authCookie);
HttpPost post = new HttpPost(createPostUrl);
post.addHeader("User-Agent", "Mozilla/5.0");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("nonce", nonce));
nvps.add(new BasicNameValuePair("cookie", authCookie));
nvps.add(new BasicNameValuePair("status", status));
nvps.add(new BasicNameValuePair("title", title));
nvps.add(new BasicNameValuePair("content", content));
nvps.add(new BasicNameValuePair("categories", Utils.listToCommaSeparated(categories)));
nvps.add(new BasicNameValuePair("tags", Utils.listToCommaSeparated(tags)));
nvps.add(new BasicNameValuePair("author", author));
post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
CloseableHttpResponse res = httpClient.execute(post);
int code = res.getStatusLine().getStatusCode();
I expect 200 OK response code.
Found it, the reason was some SVG elements in the content,after the removal of them everything is ok

Apache Http Client 4 Form Post Multi-part data

I need to post some form parameters to a server through an HTTP request (one of which is a file). So I use Apache HTTP Client like so...
HttpPost httpPost = new HttpPost(urlStr);
params = []
params.add(new BasicNameValuePair("username", "bond"));
params.add(new BasicNameValuePair("password", "vesper"));
params.add(new BasicNameValuePair("file", payload));
httpPost.setEntity(new UrlEncodedFormEntity(params));
httpPost.setHeader("Content-type", "multipart/form-data");
CloseableHttpResponse response = httpclient.execute(httpPost);
The server returns an error, stack trace is..
the request was rejected because no multipart boundary was found
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:954)
at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:331)
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:351)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:156)
I understand from other posts that I need to somehow come up with a boundary, which is a string not found in the content. But how do I create this boundary in the code I have above? Should it be another parameter? Just a code sample is what I need.
As the exception says, you have not specified the "multipart boundary". This is a string that acts as a separator between the different parts in the request. But in you case it seems like you do not handle any different parts.
What you probably want to use is MultipartEntityBuilder so you don't have to worry about how it all works under the hood.
It should be Ok to do the following
HttpPost httpPost = new HttpPost(urlStr);
File payload = new File("/Users/CasinoRoyaleBank");
HttpEntity entity = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addBinaryBody("file", payload)
.addTextBody("username", "bond")
.addTextBody("password", "vesper")
.build();
httpPost.setEntity(entity);
However, here is a version that should be compatible with #AbuMariam findings below but without the use of deprecated methods/constructors.
File payload = new File("/Users/CasinoRoyaleBank");
ContentType plainAsciiContentType = ContentType.create("text/plain", Consts.ASCII);
HttpEntity entity = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("file", new FileBody(payload))
.addPart("username", new StringBody("bond", plainAsciiContentType))
.addPart("password", new StringBody("vesper", plainAsciiContentType))
.build();
httpPost.setEntity(entity);
CloseableHttpResponse response = httpclient.execute(httpPost);
The UrlEncodedFormEntity is normally not used for multipart, and it defaults to content-type application/x-www-form-urlencoded
I accepted gustf's answer because it got rid of the exception I was having and so I thought I was on the right track, but it was not complete. The below is what I did to finally get it to work...
File payload = new File("/Users/CasinoRoyaleBank")
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
entity.addPart( "file", new FileBody(payload))
entity.addPart( "username", new StringBody("bond"))
entity.addPart( "password", new StringBody("vesper"))
httpPost.setEntity( entity );
CloseableHttpResponse response = httpclient.execute(httpPost);

How to login in JIRA using REST API and POST issue

Actually my task is to post bug in JIRA from an Excel sheet.
Now I am able to post bugs in Bugzilla. Please any one help me with Java code about how to login and post bug using REST API. I have an example in perl, I would like it in java.
I tried with the following code, I'm able to login but now I would like to perform all tasks using JIRA REST API.
HttpPost httpost = new HttpPost("https://id.atlassian.com/login?continue=https://jira.atlassian.com/secure/Dashboard.jspa&application=jac");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", "sxxxxxxx#live.com"));
nvps.add(new BasicNameValuePair("password", "xxxxxxxxxn"));
nvps.add(new BasicNameValuePair("csrfToken", xcrfTokenVal));
nvps.add(new BasicNameValuePair("continue", "https://jira.atlassian.com/secure/Dashboard.jsp"));
nvps.add(new BasicNameValuePair("application", "jac"));
httpost.setEntity(new UrlEncodedFormEntity(nvps));
response = httpclient.execute(httpost);
System.out.println("Response " + response.toString());
entity = response.getEntity();
//System.out.println("Double check we've got right page " + EntityUtils.toString(entity));
System.out.println("Response from : " + response.getStatusLine());
You have to do a POST to "http://JIRA_URL/rest/auth/1/session", set a Cookie with the JSessionID to do other requests. In Jersey, basically you would do:
jsonParameters = "{\"username\":\"usernameValue\", \"password\": \"passwordValue\"}";
WebResource webResource = client.resource("http://<JIRA_URL>/rest/auth/1/session");
ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, jsonParameters);
In the response you will have the JSessionID, so you have to save this in a Cookie and use it. In Jersey:
import javax.ws.rs.core.Cookie;
...
Cookie cookie = new Cookie(jsession.getName(), jsession.getValue());
response = webResource.type(MediaType.APPLICATION_JSON).cookie(cookie)
.post(ClientResponse.class, jsonParameters);
JIRA Rest Doc:
https://docs.atlassian.com/jira/REST/6.3.1/#d2e3131

Android HTTP post with {"key" => JSON}

I've been using lots of HTTP posts in my apps recently and I've always been using this template:
HttpPost httpPost = new HttpPost(server);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name","John"));
nameValuePairs.add(new BasicNameValuePair("age",13+""));
...
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpClient.execute(httpPost);
And on the server's PHP script:
$name = $_POST['name'];
$age = $_POST['age'];
...
This has always worked perfectly. However, recently I got a request that the data should actually be a JSON itself which would contain all those key-value pairs.
To be more explicit, the PHP script has been written to do this:
$json = $_POST['data'];
$name = $json['name'];
$age = $json['age'];
...
While this is an awkwardly simple modification, I can't seem to make it work in the Android code, i.e. I can't find the correct way to add the JSON to the HTTP data.
I'm doing this:
JSONObject json = new JSONObject();
json.put("name", "John");
json.put("age", 13+"");
...
But what to do next?? How can I add this JSON to the HTTP with the key "data"?
I've tried this:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", json.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
But I'm not sure it's the right way to do it and also the server's response is signalling an error.
How should I do it? How should I GENERALLY add a JSONObject with a key, or even a JSONArray?
Thanks!
EDIT: Please don't send me to other SO links, I've looked and none is answering straight to my point.
Generally write json:
http://www.vogella.com/tutorials/AndroidJSON/article.html#androidjson_write
For your task, you don't need to put your json into a list. Just do
httpPost.setEntity(new UrlEncodedFormEntity(json.toString()));
//or else use this
httpPost.setEntity(new StringEntity(json.toString(), HTTP.UTF_8));
EDIT:
JSONObject json = new JSONObject();
json.put("name", "John");
json.put("age", 13+"");
JSONObject data = new JSONObject();
data.put("data", json.toString());
httpPost.setEntity(new UrlEncodedFormEntity(data.toString()));

HttpPost -> Redirect -> Location or body of response needed

Here is Java code that POSTs data to a website and than gets redirected as a response (status 302). It works perfectly on my PC (Eclipse, Java, Ubuntu), it does exactly what I want it to do.
I tried quite everything to post the code functionality but I just am not able to.
Java code:
// Preparing the CLIENT and POST Method
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://na.leagueoflegends.com/ladders/solo-5x5");
try {
// Add your POST METHOD attributes
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("op", "Search"));
nameValuePairs.add(new BasicNameValuePair("player", "Jaiybe"));
nameValuePairs.add(new BasicNameValuePair("ladder_id", "3"));
nameValuePairs.add(new BasicNameValuePair("form_build_id",
"form-526370b788622996caa3669e7b975ccf"));
nameValuePairs.add(new BasicNameValuePair("form_id",
"ladders_filter_form"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
// RESPONE THAT WORKS WITH JAVA
System.out.println("Location:");
String LocationHeader = response.getFirstHeader("location").getValue();
System.out.println(LocationHeader);
System.out.println();
// To get the BODY I would have to parse that again - since its not REDIRECTING automatically
HttpClient httpclient2 = new DefaultHttpClient();
HttpPost httppost2 = new HttpPost(LocationHeader);
response = httpclient2.execute(httppost2);
System.out.println("And EVEN the response body:");
System.out.println(EntityUtils.toString(response.getEntity()));
Code does:
Posts
Gets Redirected - gets header of Location
Parses the Location
And I need android to do the same. Either "Location" or body of repsonse, is ok, I dont need both.
The post: http://www.anddev.org/networking-database-problems-f29/httppost-clientprotocolexception-t56118.html
I have found the problem!
httpclient.getParams().setParameter("http.protocol.version",
HttpVersion.HTTP_1_0);
Just changing this one line - version 1_0 works and 1_1 does not. Don't ask me why :)
Thank you all!
Please try the following code. The location in the header is missing, because the page has already redirected. So we can disable redirection to get the location tag.
httpclient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
Try calling this after you create your http client so that it follows your redirect
httpclient.getParams().setParameter("http.protocol.allow-circular-redirects", true);

Categories

Resources