1. 程式人生 > >org.apache.commons.httpclient.HttpClient的使用

org.apache.commons.httpclient.HttpClient的使用

package com.httpclient1;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import com.google.gson.Gson;


/**
 * 用commons-httpclient-3.1 框架, 模擬客戶端請求
 * @since 2016-4-11
 * @version 1.0
 */
public class Client {

	public static void main(String[] args) {		
		String serviceUrl = "http://localhost:8080/MbtForSpring/test/demo/serviceOne.do";
		
		Map<String, Object> parames = new HashMap<String, Object>();
		Gson gson = new Gson();
		String json = null;
		try {
			parames.put("AppKey", "132152");
			parames.put("Ticket", "57077c8537");

			json = gson.toJson(parames);

			System.out.println("json:" + json);
			
			String str = doPost(serviceUrl, json);
			System.out.println(str);
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}
	
	/**
	 * 
	 * @param strUrl
	 * @param postString
	 * @return
	 * String
	 */
	@SuppressWarnings("deprecation")
	public static String doPost(String strUrl, String postString) {
		String receive = null;
		
		// 請求釋出在本地 Tomcat上服務
		PostMethod method = new PostMethod(strUrl);
//		PostMethod method = new PostMethod();
		try {
			HttpClient client = new HttpClient();
//			client.getHostConfiguration().setHost(new HttpHost());
			
			//請求 網路上的服務, 用這種方式請求本地,返回一個Html頁面
//			client.getHostConfiguration().setHost(new URI(strUrl));
			
			method.setRequestHeader("Content-type", "application/json; charset=UTF-8");
			method.setRequestHeader("Accept", "application/json; charset=UTF-8");
			// 設定為預設的重試策略
			method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
			
			// 4, 設定請求引數(請求內容)
/*			NameValuePair pair1 = new NameValuePair("key", "value");
			NameValuePair pair2 = new NameValuePair("key", "value");
			method.setRequestBody(new NameValuePair[]{pair1, pair2} );*/

			method.setRequestBody(postString);
			int rspCode = client.executeMethod(method);
			//
			System.out.println("rspCode:" + rspCode);
			receive = method.getResponseBodyAsString();
			System.out.println("receive:" + receive);
			return receive;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			method.releaseConnection();
		}
		return receive;
	}
}