为了账号安全,请及时绑定邮箱和手机立即绑定

在Java中使用HttpClient的HTTP基本身份验证?

在Java中使用HttpClient的HTTP基本身份验证?

SMILET 2019-07-19 15:42:47
在Java中使用HttpClient的HTTP基本身份验证?我试图在Java中模仿这个curl命令的功能:curl --basic --user username:password -d "" http://ipaddress/test/login我使用CommonsHttpClient3.0编写了以下代码,但最终得到了500 Internal Server Error从服务器。有人能告诉我做错什么了吗?public class HttpBasicAuth {     private static final String ENCODING = "UTF-8";     /**      * @param args      */     public static void main(String[] args) {         // TODO Auto-generated method stub         try {             HttpClient client = new HttpClient();             client.getState().setCredentials(                     new AuthScope("ipaddress", 443, "realm"),                     new UsernamePasswordCredentials("test1", "test1")                     );             PostMethod post = new PostMethod(                     "http://address/test/login");             post.setDoAuthentication( true );             try {                 int status = client.executeMethod( post );                 System.out.println(status + "\n" + post.getResponseBodyAsString());             } finally {                 // release any connection resources used by the method                 post.releaseConnection();             }         } catch (Exception e) {             // TODO Auto-generated catch block             e.printStackTrace();         }     }    }
查看完整描述

3 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超3个赞

您是否尝试过(使用HttpClient版本4):


String encoding = Base64Encoder.encode(user + ":" + pwd);

HttpPost httpPost = new HttpPost("http://host:post/test/login");

httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoding);


System.out.println("executing request " + httpPost.getRequestLine());

HttpResponse response = httpClient.execute(httpPost);

HttpEntity entity = response.getEntity();


查看完整回答
反对 回复 2019-07-19
  • 3 回答
  • 0 关注
  • 1636 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信