1

I have something that looks like this:

POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded

grant_type=assertion&assertion_type=http%3A%2F%2Foauth.net%2Fgrant_type%2Fjwt%2F1.0%2Fbearer&assertion=eyJhbGciOiJSUzI1NiIs

How would I go about using this in Java? I have all the information already so I wouldn't need to parse it.

Basically I need to POST with 3 different data and using curl has been working for me but I need to do it in java:

curl -d 'grant_type=assertion&assertion_type=http%3A%2F%2Foauth.net%2Fgrant_type%2Fjwt%2F1.0%2Fbearer&assertion=eyJhbGciOiJSUzI1NiIsInR5i' https://accounts.google.com/o/oauth2/token

I cut off some data so its easier to read so it wont work.

So a big problem is that the curl would work while most tutorials I try for Java would give me HTTP response error 400.

Like should I be encoding the date like this:

String urlParameters = URLEncoder.encode("grant_type", "UTF-8") + "="+ URLEncoder.encode("assertion", "UTF-8") + "&" + URLEncoder.encode("assertion_type", "UTF-8") + "=" + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8") + "&" + URLEncoder.encode("assertion", "UTF-8") + "=" + URLEncoder.encode(encodedMessage, "UTF-8");

or not:

String urlParameters ="grant_type=assertion&assertion_type=http://oauth.net/grant_type/jwt/1.0/bearer&assertion=" + encodedMessage;

Using this as the code:

URL url = new URL(targetURL);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);


OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

writer.write(urlParameters);
writer.flush();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
     System.out.println(line);
}
writer.close();
reader.close();
Dragonfly
  • 4,261
  • 7
  • 34
  • 60

2 Answers2

4

Use something like HttpClient or similar.

It can post pre-URL-encoded data to a URI, although I don't know if you could just throw a complete request body at it--might need to parse it out, but there are likely libraries for that as well.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
2

Here's a simple example of Apache HttpClient with request body from their docs (slightly modified to show how the execute works):

HttpClient client = new HttpClient();
PostMethod post = new PostMethod("http://jakarata.apache.org/");
NameValuePair[] data = {
    new NameValuePair("user", "joe"),
    new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
int returnCode = client.execute(post);
// check return code ...
InputStream in = post.getResponseBodyAsStream();

See the Apache HttpClient site for more info, examples and tutorials. This link might help you too.

stephen.hanson
  • 9,014
  • 2
  • 47
  • 53