HttpClient3.x之Get請求和Post請求示例

HttpClient的支持在HTTP/1.1規範中定義的所有的HTTP方法:GET, HEAD, POST, PUT, DELETE, TRACE 和 OPTIONS。每有一個方法都有一個對應的類:HttpGet,HttpHead,HttpPost,HttpPut,HttpDelete,HttpTrace和HttpOptions。所有的這些類均實現了HttpUriRequest接口,故可以作爲execute的執行參數使用。請求URI是能夠應用請求的統一資源標識符。 HTTP請求的URI包含一個協議計劃protocol scheme,主機名host name,,可選的端口optional port,資源的路徑resource path,可選的查詢optional query和可選的片段optional fragment。

 

head,put,delete,trace HttpClient支持這些方法,
大多數瀏覽器不支持這些方法,原因是Html 4中對 FORM 的method方法只支持兩個get和post,很多瀏覽器還都依然是基於html4的。

 

通常會在JAVA中通過代碼調用URL進行遠端方法調用,這些方法有的是Get請求方式的,有的是POST請求方式的,爲此,總結一例,貼出以便查閱。

依賴JAR包有:commons-codec.jar,commons-httpclient.jar,commons-logging.jar。

package com.wujintao.httpclient;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.junit.Test;

public class TestCase {

	@Test
	public void testGetRequest() throws IllegalStateException, IOException {
		HttpClient client = new HttpClient();
		StringBuilder sb = new StringBuilder();
		InputStream ins = null;
		// Create a method instance.
		GetMethod method = new GetMethod("http://www.baidu.com");
		// Provide custom retry handler is necessary
		method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler(3, false));
		try {
			// Execute the method.
			int statusCode = client.executeMethod(method);
			System.out.println(statusCode);
			if (statusCode == HttpStatus.SC_OK) {
				ins = method.getResponseBodyAsStream();
				byte[] b = new byte[1024];
				int r_len = 0;
				while ((r_len = ins.read(b)) > 0) {
					sb.append(new String(b, 0, r_len, method
							.getResponseCharSet()));
				}
			} else {
				System.err.println("Response Code: " + statusCode);
			}
		} catch (HttpException e) {
			System.err.println("Fatal protocol violation: " + e.getMessage());
		} catch (IOException e) {
			System.err.println("Fatal transport error: " + e.getMessage());
		} finally {
			method.releaseConnection();
			if (ins != null) {
				ins.close();
			}
		}
		System.out.println(sb.toString());
	}

	@Test
	public void testPostRequest() throws HttpException, IOException {
		HttpClient client = new HttpClient();
		PostMethod method = new PostMethod("http://www.baidu.com/getValue");
		method.setRequestHeader("Content-Type",
				"application/x-www-form-urlencoded;charset=gb2312");
		NameValuePair[] param = { new NameValuePair("age", "11"),
				new NameValuePair("name", "jay"), };
		method.setRequestBody(param);
		int statusCode = client.executeMethod(method);
		System.out.println(statusCode);
		method.releaseConnection();
	}

}


發佈了203 篇原創文章 · 獲贊 1627 · 訪問量 219萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章