带有身份验证的HttpClient请求

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.UsernamePasswordCredentials;

import org.apache.commons.httpclient.methods.PostMethod;

import org.apache.commons.httpclient.methods.StringRequestEntity;

import org.apache.commons.httpclient.auth.AuthScope;

public class TestHttp {

public static void main(String[] args) {

try {

HttpClient httpClient = new HttpClient();

PostMethod method=new PostMethod("url");

UsernamePasswordCredentials creds = new UsernamePasswordCredentials("user", "pwd"); httpClient.getParams().setAuthenticationPreemptive(true); httpClient.getState().setCredentials(AuthScope.ANY, creds);

method.setDoAuthentication(true);

String payload="请求体内容 ";

method.setRequestEntity(new StringRequestEntity(payload, "text/html", "utf-8"));

httpClient.executeMethod(method);

System.out.println(method.getStatusCode());

System.out.println(method.getResponseBodyAsString());

}catch (Exception e) {

e.printStackTrace();

}

}

}

你可能感兴趣的:(java,httpclient)