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包自行导入

你可能感兴趣的:(JAVA调用http接口)