记录java HttpPost 密码登录鉴权和提交表单的案例,使用的是httppost而不是HttpURLConnection
httpost需要下面的依赖
org.apache.httpcomponents
httpclient
String content = null;
CloseableHttpClient httpClient =null;
CloseableHttpResponse httpresponse = null;
try {
httpClient = HttpClients.createDefault();
//用户名密码登录鉴权
HttpClientContext context = HttpClientContext.create();
CredentialsProvider credsProvider = new BasicCredentialsProvider();
Credentials credentials = new org.apache.http.auth.UsernamePasswordCredentials(clientId, clientSecret);
credsProvider.setCredentials(AuthScope.ANY, credentials);
context.setCredentialsProvider(credsProvider);
HttpPost httpPost=new HttpPost(url);
//提交表单信息
List params=new ArrayList();
params.add(new BasicNameValuePair("grant_type","client_credentials"));
httpPost.setEntity(new UrlEncodedFormEntity(params));
httpresponse = httpClient.execute(httpPost,context);
content = EntityUtils.toString(httpresponse.getEntity());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(httpresponse!=null)httpresponse.close();
if(httpClient!=null)httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}