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

java | 2019-11-19 14:26:38

记录java HttpPost 密码登录鉴权和提交表单的案例,使用的是httppost而不是HttpURLConnection

httpost需要下面的依赖

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

 



        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<NameValuePair> params=new ArrayList<NameValuePair>();
            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();
            }
        }

 

登录后即可回复 登录 | 注册
    
关注编程学问公众号