使用HttpClient進行HTTP BASIC驗證

1.maven項目引入HttpClient依賴,或導入jar包apache

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

2.編寫方法,輸入定義的用戶名、密碼,返回一個httpClient對象maven

public static CloseableHttpClient getHttpClient(){
    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(USERNAME, PASSWORD);
    provider.setCredentials(AuthScope.ANY, credentials);
    return  HttpClients.custom().setDefaultCredentialsProvider(provider).build();
}

3.將返回的httpClient對象使用HttpClient發出get或post等請求ide

public static String createStream(String url, String name) {
    CloseableHttpClient httpClient = getHttpClient();
    HttpPost httpPost = new HttpPost(url);
    String s = "";
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("name", name));
    try {
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,"UTF-8");
        httpPost.setEntity(formEntity);
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        s = EntityUtils.toString(entity);
        System.out.println(s);
        httpClient.close();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return s;
}
相關文章
相關標籤/搜索