【发布时间】:2012-10-15 20:18:41
【问题描述】:
我正在尝试使用 HttpClient(HttpComponents) 创建一个 HttpPost。这是我的代码:
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(
"https://accounts.google.com/o/oauth2/token");
post.addHeader("accept", "application/json");
post.addHeader("Content-Type", "application/json");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("code", new String(code.getBytes(), Charset.forName("UTF-8"))));
nvps.add(new BasicNameValuePair("client_id", "googleClientId"));
nvps.add(new BasicNameValuePair("redirect_uri", "http://localhost:8080/myapp/test"));
nvps.add(new BasicNameValuePair("client_secret", "ClientSecret"));
nvps.add(new BasicNameValuePair("grant_type", "authorization_code"));
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse resp = httpClient.execute(post);
if (resp.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ resp.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((resp.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
res = res + output;
}
System.out.println(output);
httpClient.getConnectionManager().shutdown();
} catch(Exception e){
e.printStackTrace();
}
System.out.println(res);
我得到一个400 代码。我怀疑这是因为我设置的所有参数都包含特殊字符,例如 _ . and / 并且它们被转义了。我怎样才能避免这种情况?还是我错过了真正的问题?
【问题讨论】:
-
@Nambari 这是帖子,所以我与网址无关。
-
@Nambari 我错过了什么?我是否以某种方式在 URL 中发送参数?
-
看来你是。您能否一一添加并缩小可能导致问题的参数/。
-
@Nambari 显然我错了。这是
redirect_uri。你有使用 OAuth2 的经验吗?
标签: java post httpclient