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

2 に答える 2

4

HttpClientなどを使用します。

事前にURLエンコードされたデータをURIに投稿できますが、完全なリクエスト本文を投げることができるかどうかはわかりません。解析する必要があるかもしれませんが、そのためのライブラリもある可能性があります。

于 2012-06-01T21:12:48.727 に答える
2

これは、ドキュメントからのリクエスト本文を使用した Apache HttpClient の簡単な例です(実行がどのように機能するかを示すために少し変更されています)。

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

詳細、例、チュートリアルについては、Apache HttpClient サイトを参照してください。このリンクも役立つかもしれません。

于 2012-06-01T21:25:08.190 に答える