我想使用客户端凭据方法来获取访问令牌 我需要发送这样的请求:
https://openapi.baidu.com/oauth/2.0/token?
grant_type=client_credentials&
client_id=SOME_CLIENT_ID
client_secret= A_CLIENT_SECRET
client_id:
API密钥
client_secret:
密钥
但是当执行到httpResponse = httpclient.execute(httpRequest)
时,它会导致错误......,我无法弄清楚发生了什么......
baidu参考:here
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
String result = null;
try {
result = sendRequest();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tv.setText(result);
setContentView(tv);
}
private String sendRequest() throws IOException{
Log.i("sendRequest", "in");
String httpUrl = "https://openapi.baidu.com/oauth/2.0/token?";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(httpUrl);
List<NameValuePair> params = new ArrayList<NameValuePair>(3);
params.add(new BasicNameValuePair("grant_type", "client_credentials"));
params.add(new BasicNameValuePair("client_id", "MY_ID"));
params.add(new BasicNameValuePair("client_secret", "MY_SECRET"));
httpRequest.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = null;
try{
httpResponse = httpclient.execute(httpRequest);
}catch(ClientProtocolException e){
}catch(IOException e){
}
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
String strResult = EntityUtils.toString(httpResponse.getEntity());
return strResult;
}
return null;
}
}