1. 程式人生 > >JAVA呼叫http介面

JAVA呼叫http介面

程式碼如下:

package demo.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class HttpUtil {


	public static String doRequest(String url, String param) {

		// 初始化引數
		InputStream inputStream = null;
		String response = "";
		BufferedReader br = null;
		PostMethod postMethod = null;

		// 建立例項
		HttpClient httpclient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager());

		// 設定介面超時時間
		httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

		try {
			postMethod = new PostMethod(url);
			httpclient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

			// 設定http header
			postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			postMethod.setRequestHeader("username", "user1");
			postMethod.setRequestHeader("password", "user001");
			
			// 設定傳入引數
			NameValuePair message = new NameValuePair("userName", param);
			postMethod.setRequestBody(new NameValuePair[] { message });

			// 執行介面請求
			int statusCode1 = httpclient.executeMethod(postMethod);

			// 判斷返回值
			if (statusCode1 != HttpStatus.SC_OK) {
				System.out.println("Method is wrong " + postMethod.getStatusLine() + "----" + statusCode1);
				return null;
			} else {
				// 獲取返回值
				inputStream = postMethod.getResponseBodyAsStream();
				br = new BufferedReader(new InputStreamReader(inputStream));
				StringBuffer stringBuffer = new StringBuffer();
				String str = "";
				while ((str = br.readLine()) != null) {
					stringBuffer.append(str);
				}
				response = stringBuffer.toString();
			}
			return response;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				if (br != null) {
					br.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			postMethod.releaseConnection();
		}

	}
	

	public static void main(String[] args) {
		//根據使用者id 獲取DN
		String url = "";
		//使用者id
		String param = "A00040";
		String res = HttpUtil.doRequest(url, param);
		System.out.println(res);
	}

}
需要jar包自行匯入