1.maven项目引入HttpClient依赖,或导入jar包

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

2.编写方法,输入定义的用户名、密码,返回一个httpClient对象

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等请求

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;
}

GODSEULGI
11 声望5 粉丝