我正在尝试使用DefaultHTTPClient
从Java中的auth端点获取身份验证令牌这是我尝试在Java中重现的curl命令
curl -u "user:pass" -H "Content-Type:application/x-www-form-urlencoded" -X POST -d "grant_type=basic" http://auth.myCompany.com/v1/oauth2/token
这是Java代码段
DefaultHttpClient dhttpclient = new DefaultHttpClient();
String username = "user";
String password = "pass";
String uri = "http://auth.myCompany.com/v1/oauth2/token";
try
{
dhttpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
HttpPost dhttppost = new HttpPost(uri);
dhttppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
/** How to add request Body here **/
dhttppost.ADD_REQUEST_BODY(grant_type = basic??)
System.out.println("executing request " + dhttppost.getRequestLine());
HttpResponse dresponse = dhttpclient.execute(dhttppost);
System.out.println("StatusLine" + dresponse.getStatusLine() );
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
dhttpclient.getConnectionManager().shutdown();
}
添加以下内容会产生400错误请求
dhttppost.setEntity(new StringEntity("grant_type=basic"));
这也会导致错误的请求错误
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("grant_type", "basic"));
dhttppost.setEntity(new UrlEncodedFormEntity(params));
有些日志记录给了我以下
DEBUG [2016-06-28 19:08:52,059] org.apache.http.client.protocol.RequestTargetAuthentication: Target auth state: UNCHALLENGED
这是预期的吗?