在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();
添加回答
舉報
0/150
提交
取消