绑定完请刷新页面
取消
刷新

分享好友

×
取消 复制
common-httpclient 用户名密码认证示例
2020-02-05 18:16:31

    复制代码

import java.io.IOException;  
import java.util.ArrayList;  
import java.util.List;  
  
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;  
import org.apache.commons.httpclient.Header;  
import org.apache.commons.httpclient.HttpClient;  
import org.apache.commons.httpclient.HttpException;  
import org.apache.commons.httpclient.HttpStatus;  
import org.apache.commons.httpclient.UsernamePasswordCredentials;  
import org.apache.commons.httpclient.auth.AuthScope;  
import org.apache.commons.httpclient.methods.GetMethod;  
import org.apache.commons.httpclient.params.HttpMethodParams;  
  
public class HttpClientUse {  
  
    public static void main(String[] args) throws HttpException, IOException {  
        HttpClient httpClient = new HttpClient();  
        //需要验证  
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials("guest", "guest");  

        httpClient.getState().setCredentials(AuthScope.ANY, creds); 
        
  
        //设置http头  
        List <Header> headers = new ArrayList <Header>();  
        headers.add(new Header("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"));  
        httpClient.getHostConfiguration().getParams().setParameter("http.default-headers", headers);  
  
        GetMethod method = new GetMethod("http://localhost:15672/api/exchanges/%2F/amq.direct");
        method.setDoAuthentication(true);
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,  
                new DefaultHttpMethodRetryHandler(3, false));  
        try {  
            int statusCode = httpClient.executeMethod(method);  
            if (statusCode != HttpStatus.SC_OK) {  
                System.out.println("Method failed code="+statusCode+": " + method.getStatusLine());  
  
            } else {  
                System.out.println(new String(method.getResponseBody(), "utf-8"));  
            }  
        } finally {  
            method.releaseConnection();  
        }  
    }  
}  
复制代码
分享好友

分享这个小栈给你的朋友们,一起进步吧。

凉城时光
创建时间:2019-12-04 10:57:57
朋友 我们一起聊运维
展开
订阅须知

• 所有用户可根据关注领域订阅专区或所有专区

• 付费订阅:虚拟交易,一经交易不退款;若特殊情况,可3日内客服咨询

• 专区发布评论属默认订阅所评论专区(除付费小栈外)

栈主、嘉宾

查看更多
  • 我没
    栈主

小栈成员

查看更多
  • unnamed personq
  • unnamed personq
  • bluetooth
  • amadan
戳我,来吐槽~