java post 登陆_java HttpPost 密码登录和提交表单的案例

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

}

}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部