http請求一個servlet(接口)地址

以前測試一個自己寫的接口總是用火狐瀏覽器的httpRequester進行請求,但是那個東西並不準確(有的時候能捕捉到沒有被捕獲的異常),而且後臺上要跟其它的平臺進行數據交互,想自己寫一個http請求小方法然後進行測試,後臺也能用上。MDZZ研究一上午,中午想明白了遂寫代碼測試成功,貼出來記錄一下。

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;

import com.alibaba.fastjson.JSONObject;

public class HttpClientTest {

	public static void main(String[] args) throws HttpException, IOException {
		//請求地址
		String url="http://xxxx:xxxx/xxxx/xxxxServlet";
		//組裝請求數據
		JSONObject json=new JSONObject();
		JSONObject requestJson=new JSONObject();
		json.put("A", "A");
		json.put("B", "B");
		requestJson.put("C", "C");
		requestJson.put("D", "D");
		json.put("request", requestJson);
		
		/******正式的數據請求******/
		HttpClient client=new HttpClient();
		PostMethod method=new PostMethod(url);
		byte[] bytes = json.toString().getBytes("UTF-8");
		InputStream inputStream = new ByteArrayInputStream(bytes,0,bytes.length);
		//setRequestBody方法在http3.1之後被替換成setRequestEntity
		RequestEntity re=new InputStreamRequestEntity(inputStream,bytes.length,"charset=utf-8");
		method.setRequestEntity(re);
		
		method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "GBK");
		//設置超時的代碼段
		HttpConnectionManagerParams managerParams = client.getHttpConnectionManager().getParams();
		//設置連接超時時間(單位毫秒)
		managerParams.setConnectionTimeout(10000);
		//查看狀態
		int status = client.executeMethod(method);
		if (status != HttpStatus.SC_OK) {
			System.out.println( "連接" + url+ "出錯!錯誤代碼爲:" + status);
			throw new IllegalStateException("Method failed: "+ method.getStatusLine());
		}
		
		//處理返回的數據
		InputStream txtis = method.getResponseBodyAsStream();
		/* eclipse 環境開發環境遷移之後導致的返回報文亂碼問題修改 */
		BufferedReader br = new BufferedReader(new InputStreamReader(txtis,Charset.forName("UTF-8")));
		
		//爲了更直觀的看到返回的數據而寫的方法
		StringBuffer html = new StringBuffer(100);
		String tempbf;
		while ((tempbf = br.readLine()) != null) {
			html.append(tempbf);
		}
		method.releaseConnection();
		
		System.out.println(html.toString());
	}
	
}


大致就是這樣的請求方式,經測試暫無問題。還有一種接口的請求方式原理上大致就是在地址後面拼上參數然後整個長地址進行請求,只需把url後面拼完參數整個的地址請

求即可。上述方法如果有亂碼的情況改改請求格式即可。













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