天天看點

HttpClient 學習整理

HTTP 鍗忚鍙兘鏄幇鍦?Internet 涓婁嬌鐢ㄥ緱鏈€澶氥€佹渶閲嶈鐨勫崗璁簡锛岃秺鏉ヨ秺澶氱殑 Java 搴旂敤绋嬪簭闇€瑕佺洿鎺ラ€氳繃 HTTP 鍗忚鏉ヨ闂綉缁滆祫婧愩€傝櫧鐒跺湪 JDK 鐨?java.net 鍖呬腑宸茬粡鎻愪緵浜嗚闂?HTTP 鍗忚鐨勫熀鏈姛鑳斤紝浣嗘槸瀵逛簬澶ч儴鍒嗗簲鐢ㄧ▼搴忔潵璇達紝JDK 搴撴湰韬彁渚涚殑鍔熻兘杩樹笉澶熶赴瀵屽拰鐏墊椿銆侶ttpClient 鏄?Apache Jakarta Common 涓嬬殑瀛愰」鐩紝鐢ㄦ潵鎻愪緵楂樻晥鐨勩€佹渶鏂扮殑銆佸姛鑳戒赴瀵岀殑鏀寔 HTTP 鍗忚鐨勫鎴風缂栫▼宸ュ叿鍖咃紝骞朵笖瀹冩敮鎸?HTTP 鍗忚鏈€鏂扮殑鐗堟湰鍜屽緩璁€侶ttpClient 宸茬粡搴旂敤鍦ㄥ緢澶氱殑椤圭洰涓紝姣斿 Apache Jakarta 涓婂緢钁楀悕鐨勫彟澶栦袱涓紑婧愰」鐩?Cactus 鍜?HTMLUnit 閮戒嬌鐢ㄤ簡 HttpClient锛屾洿澶氫嬌鐢?HttpClient 鐨勫簲鐢ㄥ彲浠ュ弬瑙乭ttp://wiki.apache.org/jakarta-httpclient/HttpClientPowered銆侶ttpClient 椤圭洰闈炲父娲昏穬锛屼嬌鐢ㄧ殑浜鴻繕鏄潪甯稿鐨勩€?

Commons-httpclient鏄笓闂ㄨ璁℃潵绠€鍖朒TTP瀹㈡埛绔笌鏈嶅姟鍣ㄨ繘琛屽悇绉嶉€氳缂栫▼銆傞€氳繃瀹冨彲浠ヨ鍘熸潵寰堝ご鐤肩殑浜嬫儏鐜闆湪杞繪澗鐨勮В鍐籌紝渚嬪浣犱笉鍐嶇鏄疕TTP鎴栬€匟TTPS鐨勯€氳鏂瑰紡锛屽憡璇夊畠浣犳兂浣跨敤HTTPS鏂瑰紡锛屽墿涓嬬殑浜嬫儏浜ょ粰httpclient鏇誇綘瀹屾垚銆?

涓嬮潰浠ュ嚑涓皬渚嬪瓙鏉ヨ鏄巋ttpclient鐨勪嬌鐢ㄦ柟娉?

1銆佷嬌鐢╣et鎴杙ost鏂規硶鑾峰緱杩滅▼鐨剈rl鍦闆潃鐨勭綉椤靛唴瀹?

public class SimpleClient {

public static void main(String[] args) throws IOException {

HttpClient client = new HttpClient();

// 璁劇疆浠g悊鏈嶅姟鍣ㄥ湴鍧€鍜岀鍙?

// client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);

// 浣跨敤 GET 鏂規硶 锛屽鏋滄湇鍔″櫒闇€瑕侀€氳繃 HTTPS 杩炴帴锛岄偅鍙渶瑕佸皢涓嬮潰 URL 涓殑 http 鎹㈡垚 https

HttpMethod method = new GetMethod("http://www.baidu.com");

// 浣跨敤POST鏂規硶

//HttpMethod method = new PostMethod("http://www.baidu.com");

client.executeMethod(method);

// 鎵撳嵃鏈嶅姟鍣ㄨ繑鍥炵殑鐘舵€?

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

// 鎵撳嵃杩斿洖鐨勪俊鎭?

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

// 閲婃斁杩炴帴

method.releaseConnection();

}

}

2銆佷互GET鎴栬€匬OST鏂瑰紡鍚戠綉椤墊彁浜ゅ弬鏁?

public String postMethod(boolean needAuth,String InterBiz ,String userName,String password,String picPath, String msg) throws HttpException, IOException{

HttpClient client = new HttpClient();

// client.getHostConfiguration().setHost("api.minicloud.com.cn", 80,"http");

PostMethod method = new PostMethod(InterBiz);

MultipartRequestEntity mrp=null;

if (needAuth) {

client.getParams().setAuthenticationPreemptive(true);

client.getState().setCredentials(

new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT,AuthScope.ANY_REALM),

new UsernamePasswordCredentials(userName, password));

method.setDoAuthentication(true);

}

msg = URLEncoder.encode(msg, "UTF-8");

StringPart sp = new StringPart("status", msg);

if(picPath==null|| picPath.trim().equals("")){

mrp = new MultipartRequestEntity(new Part[] {sp }, method.getParams());

}else{

File file = new File(picPath);

FilePart fp = new FilePart("pic", file.getName(), file,

new MimetypesFileTypeMap().getContentType(file), "UTF-8");

fp.setTransferEncoding("binary");

mrp = new MultipartRequestEntity(new Part[] {

sp,fp}, method.getParams());

}

method.setParameter("status", msg);

method.setRequestEntity(mrp);

client.executeMethod(method);

String jsonData=new String(method.getResponseBodyAsString().getBytes("gbk"));

method.releaseConnection();

return jsonData;

}

3锛?澶勭悊椤甸潰閲嶅畾鍚?

鍦↗SP/Servlet缂栫▼涓璻esponse.sendRedirect鏂規硶灏辨槸浣跨敤HTTP鍗忚涓殑閲嶅畾鍚戞満鍒躲€傚畠涓嶫SP涓殑<jsp:forward 鈥?gt;鐨勫尯鍒湪浜庡悗鑰呮槸鍦ㄦ湇鍔″櫒涓疄鐜伴〉闈㈢殑璺寵漿锛屼篃灏辨槸璇村簲鐢ㄥ鍣ㄥ姞杞戒簡鎵€瑕佽煩杞殑椤甸潰鐨勫唴瀹瑰苟杩斿洖缁欏鎴風锛涜€屽墠鑰呮槸杩斿洖涓€涓姸鎬佺爜锛岃繖浜涚姸鎬佺爜鐨勫彲鑳藉€艱涓嬭〃锛岀劧鍚庡鎴風璇誨彇闇€瑕佽煩杞埌鐨勯〉闈㈢殑URL骞堕噸鏂闆姞杞芥柊鐨勯〉闈€傚氨鏄繖鏍蜂竴涓繃绋嬶紝鎵€浠ユ垜浠紪绋嬬殑鏃跺€欏氨瑕侀€氳繃HttpMethod.getStatusCode()鏂規硶鍒ゆ柇杩斿洖鍊兼槸鍚︿負涓嬭〃涓殑鏌愪釜鍊兼潵鍒ゆ柇鏄惁闇€瑕佽煩杞€傚鏋滃凡缁忕‘璁ら渶瑕佽繘琛岄〉闈㈣煩杞簡锛岄偅涔堝彲浠ラ€氳繃璇誨彇HTTP澶翠腑鐨刲ocation灞炴€ф潵鑾峰彇鏂扮殑鍦闆潃銆?

鐘舵€佺爜

瀵瑰簲 HttpServletResponse 鐨勫父閲?

璇︾粏鎻忚堪

301

SC_MOVED_PERMANENTLY

椤甸潰宸茬粡姘鎬箙绉誨埌鍙﹀涓€涓柊鍦闆潃

302

SC_MOVED_TEMPORARILY

椤甸潰鏆傛椂绉誨姩鍒闆彟澶栦竴涓柊鐨勫湴鍧€

303

SC_SEE_OTHER

瀹㈡埛绔姹傜殑鍦闆潃蹇呴』閫氳繃鍙﹀鐨?URL 鏉ヨ闂?

307

SC_TEMPORARY_REDIRECT

鍚?SC_MOVED_TEMPORARILY

涓嬮潰鐨勪唬鐮佺墖娈墊紨绀哄浣曞鐞嗛〉闈㈢殑閲嶅畾鍚?

client.executeMethod(post);

System.out.println(post.getStatusLine().toString());

post.releaseConnection();

// 妫€鏌ユ槸鍚﹂噸瀹氬悜

int statuscode = post.getStatusCode();

if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {

// 璇誨彇鏂扮殑 URL 鍦闆潃

Headerheader=post.getResponseHeader("location");

if (header!=null){

Stringnewuri=header.getValue();

if((newuri==null)||(newuri.equals("")))

newuri="/";

GetMethodredirect=newGetMethod(newuri);

client.executeMethod(redirect);

System.out.println("Redirect:"+redirect.getStatusLine().toString());

redirect.releaseConnection();

}else

System.out.println("Invalid redirect");

}

鎴戜滑鍙互鑷缂栧啓涓や釜JSP椤甸潰锛屽叾涓竴涓〉闈㈢敤response.sendRedirect鏂規硶閲嶅畾鍚戝埌鍙﹀涓€涓〉闈㈢敤鏉ユ祴璇曚笂闈㈢殑渚嬪瓙銆?

4锛?妯℃嫙杈撳叆鐢ㄦ埛鍚嶅拰鍙d護杩涜鐧誨綍

鏈皬鑺傚簲璇ヨ鏄疕TTP瀹㈡埛绔紪绋嬩腑鏈€甯哥瑙佺殑闂锛屽緢澶氱綉绔欑殑鍐呭閮藉彧鏄娉ㄥ唽鐢ㄦ埛鍙鐨勶紝杩欑鎯呭喌涓嬪氨蹇呴』瑕佹眰浣跨敤姝g‘鐨勭敤鎴峰悕鍜屽彛浠ょ櫥褰曟垚鍔熷悗锛屾柟鍙祻瑙堝埌鎯寵鐨勯〉闈€傚洜涓篐TTP鍗忚鏄棤鐘舵€佺殑锛屼篃灏辨槸杩炴帴鐨勬湁鏁堟湡鍙檺浜庡綋鍓嶈姹傦紝璇鋒眰鍐呭缁撴潫鍚庤繛鎺ュ氨鍏抽棴浜嗐€傚湪杩欑鎯呭喌涓嬩負浜嗕繚瀛樼敤鎴風殑鐧誨綍淇℃伅蹇呴』浣跨敤鍒癈ookie鏈哄埗銆備互JSP/Servlet涓轟緥锛屽綋娴忚鍣ㄨ姹備竴涓狫SP鎴栬€呮槸Servlet鐨勯〉闈㈡椂锛屽簲鐢ㄦ湇鍔″櫒浼氳繑鍥炰竴涓弬鏁幫紝鍚嶄負jsessionid锛堝洜涓嶅悓搴旂敤鏈嶅姟鍣ㄨ€屽紓锛夛紝鍊兼槸涓€涓緝闀跨殑鍞竴瀛楃涓茬殑Cookie锛岃繖涓瓧绗︿覆鍊間篃灏辨槸褰撳墠璁塊棶璇ョ珯鐐圭殑浼氳瘽鏍囪瘑銆傛祻瑙堝櫒鍦ㄦ瘡璁塊棶璇ョ珯鐐圭殑鍏朵粬椤甸潰鏃跺€欓兘瑕佸甫涓妀sessionid杩欐牱鐨凜ookie淇℃伅锛屽簲鐢ㄦ湇鍔″櫒鏍規嵁璇誨彇杩欎釜浼氳瘽鏍囪瘑鏉ヨ幏鍙栧搴旂殑浼氳瘽淇℃伅銆?

瀵逛簬闇€瑕佺敤鎴風櫥褰曠殑缃戠珯锛屼竴鑸湪鐢ㄦ埛鐧誨綍鎴愬姛鍚庝細灏嗙敤鎴瘋祫鏂欎繚瀛樺湪鏈嶅姟鍣ㄧ殑浼氳瘽涓紝杩欐牱褰撹闂埌鍏朵粬鐨勯〉闈㈡椂鍊欙紝搴旂敤鏈嶅姟鍣ㄦ牴鎹祻瑙堝櫒閫佷笂鐨凜ookie涓鍙栧綋鍓嶈姹傚搴旂殑浼氳瘽鏍囪瘑浠ヨ幏寰楀搴旂殑浼氳瘽淇℃伅锛岀劧鍚庡氨鍙互鍒ゆ柇鐢ㄦ埛璧勬枡鏄惁瀛樺湪浜庝細璇濅俊鎭腑锛屽鏋滃瓨鍦ㄥ垯鍏佽璁塊棶椤甸潰锛屽惁鍒欒煩杞埌鐧誨綍椤甸潰涓姹傜敤鎴瘋緭鍏ュ笎鍙峰拰鍙d護杩涜鐧誨綍銆傝繖灏辨槸涓€鑸嬌鐢↗SP寮€鍙戠綉绔欏湪澶勭悊鐢ㄦ埛鐧誨綍鐨勬瘮杈冮€氱敤鐨勬柟娉曘€?

杩欐牱涓€鏉ワ紝瀵逛簬HTTP鐨勫鎴風鏉ヨ锛屽鏋滆璁塊棶涓€涓彈淇濇姢鐨勯〉闈㈡椂灏卞繀椤繪ā鎷熸祻瑙堝櫒鎵€鍋氱殑宸ヤ綔锛岄鍏堝氨鏄姹傜櫥褰曢〉闈紝鐒跺悗璇誨彇Cookie鍊鹼紱鍐嶆璇鋒眰鐧誨綍椤甸潰骞跺姞鍏ョ櫥褰曢〉鎵€闇€鐨勬瘡涓弬鏁幫紱鏈€鍚庡氨鏄姹傛渶缁堟墍闇€鐨勯〉闈€傚綋鐒跺湪闄ょ涓€娆¤姹傚鍏朵粬鐨勮姹傞兘闇€瑕侀檮甯︿笂Cookie淇℃伅浠ヤ究鏈嶅姟鍣ㄨ兘鍒ゆ柇褰撳墠璇鋒眰鏄惁宸茬粡閫氳繃楠岃瘉銆傝浜嗚繖涔堝锛屽彲鏄鏋滀綘浣跨敤httpclient鐨勮瘽锛屼綘鐢氳嚦杩炰竴琛屼唬鐮侀兘鏃犻渶澧炲姞锛屼綘鍙渶瑕佸厛浼犻€掔櫥褰曚俊鎭墽琛岀櫥褰曡繃绋嬶紝鐒跺悗鐩存帴璁塊棶鎯寵鐨勯〉闈紝璺熻闂竴涓櫘閫氱殑椤甸潰娌℃湁浠諱綍鍖哄埆锛屽洜涓虹被HttpClient宸茬粡甯綘鍋氫簡鎵€鏈夎鍋氱殑浜嬫儏浜嗭紝澶浜嗭紒涓嬮潰鐨勪緥瀛愬疄鐜頒簡杩欐牱涓€涓闂殑杩囩▼銆?

package http.demo;

import org.apache.commons.httpclient.*;

import org.apache.commons.httpclient.cookie.*;

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

public class FormLoginDemo {

static final String LOGON_SITE = "localhost" ;

static final int LOGON_PORT = 8080;

public static void main(String[] args) throws Exception{

HttpClient client = new HttpClient();

client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);

// 妯℃嫙鐧誨綍椤甸潰 login.jsp->main.jsp

PostMethod post = new PostMethod( "/main.jsp" );

NameValuePair name = new NameValuePair( "name" , "ld" );

NameValuePair pass = new NameValuePair( "password" , "ld" );

post.setRequestBody( new NameValuePair[]{name,pass});

int status = client.executeMethod(post);

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

post.releaseConnection();

// 鏌ョ湅 cookie 淇℃伅

CookieSpec cookiespec = CookiePolicy.getDefaultSpec();

Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/" , false , client.getState().getCookies());

if (cookies.length == 0) {

System.out.println( "None" );

} else {

for ( int i = 0; i < cookies.length; i++) {

System.out.println(cookies[i].toString());

}

}

// 璁塊棶鎵€闇€鐨勯〉闈?main2.jsp

GetMethodget=newGetMethod("/main2.jsp");

client.executeMethod(get);

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

get.releaseConnection();

}

}

5锛?鎻愪氦XML鏍煎紡鍙傛暟

鎻愪氦XML鏍煎紡鐨勫弬鏁闆緢绠€鍗曪紝浠呬粎鏄竴涓彁浜ゆ椂鍊欑殑ContentType闂锛屼笅闈㈢殑渚嬪瓙婕旂ず浠庢枃浠舵枃浠朵腑璇誨彇XML淇℃伅骞舵彁浜ょ粰鏈嶅姟鍣ㄧ殑杩囩▼锛岃杩囩▼鍙互鐢ㄦ潵娴嬭瘯Web鏈嶅姟銆?

import java.io.File;

import java.io.FileInputStream;

import org.apache.commons.httpclient.HttpClient;

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

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

public class PostXMLClient {

public static void main(String[] args) throws Exception {

File input = new File(鈥渢est.xml鈥?;

PostMethod post = new PostMethod(鈥渉ttp://localhost:8080/httpclient/xml.jsp鈥?;

// 璁劇疆璇鋒眰鐨勫唴瀹圭洿鎺ヤ粠鏂囦歡涓鍙?

post.setRequestBody( new FileInputStream(input));

if (input.length() < Integer.MAX_VALUE)

post.setRequestContentLength(input.length());

else

post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);

// 鎸囧畾璇鋒眰鍐呭鐨勭被鍨?

post.setRequestHeader( "Content-type" , "text/xml; charset=GBK" );

HttpClient httpclient = new HttpClient();

int result = httpclient.executeMethod(post);

System.out.println( "Response status code: " + result);

System.out.println( "Response body: " );

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

post.releaseConnection();

}

}

6锛?閫氳繃HTTP涓婁紶鏂囦歡

httpclient浣跨敤浜嗗崟鐙殑涓€涓狧ttpMethod瀛愮被鏉ュ鐞嗘枃浠剁殑涓婁紶锛岃繖涓被灏辨槸MultipartPostMethod锛岃绫誨凡缁忓皝瑁呬簡鏂囦歡涓婁紶鐨勭粏鑺傦紝鎴戜滑瑕佸仛鐨勪粎浠呮槸鍛婅瘔瀹冩垜浠涓婁紶鏂囦歡鐨勫叏璺緞鍗沖彲锛屼笅闈㈢殑浠g爜鐗囨婕旂ず濡備綍浣跨敤杩欎釜绫彙€?

MultipartPostMethod filePost = new MultipartPostMethod(targetURL);

filePost.addParameter( "fileName" , targetFilePath);

HttpClient client = new HttpClient();

// 鐢變簬瑕佷笂浼犵殑鏂囦歡鍙兘姣旇緝澶?, 鍥犳鍦ㄦ璁劇疆鏈€澶х殑杩炴帴瓒呮椂鏃堕棿

client.getHttpConnectionManager(). getParams().setConnectionTimeout(5000);

int status = client.executeMethod(filePost);

涓婇潰浠g爜涓紝targetFilePath鍗充負瑕佷笂浼犵殑鏂囦歡鎵€鍦ㄧ殑璺緞銆?

7锛?璁塊棶鍚敤璁よ瘉鐨勯〉闈?

鎴戜滑缁忓父浼氱鍒拌繖鏍風殑椤甸潰锛屽綋璁塊棶瀹冪殑鏃跺€欎細寮瑰嚭涓€涓祻瑙堝櫒鐨勫璇濇瑕佹眰杈撳叆鐢ㄦ埛鍚嶅拰瀵嗙爜鍚庢柟鍙紝杩欑鐢ㄦ埛璁よ瘉鐨勬柟寮忎笉鍚屼簬鎴戜滑鍦ㄥ墠闈粙缁嶇殑鍩轟簬琛ㄥ崟鐨勭敤鎴瘋韓浠介獙璇併€傝繖鏄疕TTP鐨勮璇佺瓥鐣ワ紝httpclient鏀寔涓夌璁よ瘉鏂瑰紡鍖呮嫭锛氬熀鏈€佹憳瑕佷互鍙奛TLM璁よ瘉銆傚叾涓熀鏈璇佹渶绠€鍗曘€侀€氱敤浣嗕篃鏈€涓嶅畨鍏紱鎽樿璁よ瘉鏄湪HTTP 1.1涓姞鍏ョ殑璁よ瘉鏂瑰紡锛岃€孨TLM鍒欐槸寰蔣鍏徃瀹氫箟鐨勮€屼笉鏄€氱敤鐨勮鑼冿紝鏈€鏂扮増鏈殑NTLM鏄瘮鎽樿璁よ瘉杩樿瀹夊叏鐨勪竴绉嶆柟寮忋€?

涓嬮潰渚嬪瓙鏄粠httpclient鐨凜VS鏈嶅姟鍣ㄤ腑涓嬭澆鐨勶紝瀹冪畝鍗曟紨绀哄浣曡闂竴涓璇佷繚鎶ょ殑椤甸潰锛?

import org.apache.commons.httpclient.HttpClient;

import org.apache.commons.httpclient.UsernamePasswordCredentials;

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

public class BasicAuthenticationExample {

public BasicAuthenticationExample() {

}

public static void main(String[] args) throws Exception {

HttpClient client = new HttpClient();

client.getState().setCredentials( "www.verisign.com" , "realm" , new UsernamePasswordCredentials( "username" , "password" ) );

GetMethod get = new GetMethod( "https://www.verisign.com/products/index.html" );

get.setDoAuthentication( true );

int status = client.executeMethod( get );

System.out.println(status+ "\n" + get.getResponseBodyAsString());

get.releaseConnection();

}

}

8锛?澶氱嚎绋嬫ā寮忎笅浣跨敤httpclient

澶氱嚎绋嬪悓鏃惰闂甴ttpclient锛屼緥濡傚悓鏃朵粠涓€涓珯鐐逛笂涓嬭澆澶氫釜鏂囦歡銆傚浜庡悓涓€涓狧ttpConnection鍚屼竴涓椂闂村彧鑳芥湁涓€涓嚎绋嬭闂紝涓轟簡淇濊瘉澶氱嚎绋嬪伐浣滅幆澧冧笅涓嶄駭鐢熷啿绐侊紝httpclient浣跨敤浜嗕竴涓绾跨▼杩炴帴绠$悊鍣ㄧ殑绫夥細MultiThreadedHttpConnectionManager锛岃浣跨敤杩欎釜绫誨緢绠€鍗曪紝鍙渶瑕佸湪鏋勯€燞ttpClient瀹炰緥鐨勬椂鍊欎紶鍏ュ嵆鍙紝浠g爜濡備笅锛?

MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();

HttpClient client = new HttpClient(connectionManager);

浠ュ悗灏界璁塊棶client瀹炰緥鍗沖彲銆?/body>