帶有身份驗證的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();

}

}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章