import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;public classHttpClientWithBasicAuth {public static voidmain(String args[]) {
String host= "10.104.203.166";int port = 8080;
String URI= "http://localhost/rest/channel/receipt";//创建HttpClientBuilder
httpClientBuilder httpClientBuilder =HttpClientBuilder.create();//设置BasicAuth
CredentialsProvider provider = newBasicCredentialsProvider();//Create the authentication scope
AuthScope scope = newAuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);//Create credential pair,在此处填写用户名和密码
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("root", "superuser");//Inject the credentials
provider.setCredentials(scope, credentials);//Set the default credentials provider
httpClientBuilder.setDefaultCredentialsProvider(provider);//HttpClient
CloseableHttpClient closeableHttpClient =httpClientBuilder.build();
String result= "";
HttpGet httpGet= null;
HttpResponse httpResponse= null;
HttpEntity entity= null;
httpGet= new HttpGet("http://"+host+URI);try{
httpResponse=closeableHttpClient.execute(httpGet);
entity=httpResponse.getEntity();if( entity != null){
result=EntityUtils.toString(entity);
}
}catch(ClientProtocolException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}//关闭连接
closeableHttpClient.close();// System.out.println(result);
}
}
这段代码展示了如何使用Java的HttpClient发送一个带有Basic Auth认证的HTTP POST请求。通过HttpClientBuilder创建客户端,设置BasicCredentialsProvider提供认证凭证,然后执行请求并获取响应内容。
1362

被折叠的 条评论
为什么被折叠?



