HttpClient get和HttpClient Post请求的方式获取服务器的返回数据

本文介绍了一个实用的Java HttpClient工具类实现,包括GET和POST请求的发送方法,并提供了URL拼接功能。该工具类利用了Apache HttpClient库进行HTTP请求处理,并支持自定义请求头和字符集。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.icss.daas.core.util;

import java.util.Iterator;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSONObject;

import org.apache.logging.log4j.LogManager;

public class HttpClientUtil {
	static Logger logger = LogManager.getLogger(HttpClientUtil.class);
	//static Logger logger = LogManager.getLogger(HttpClientUtil.class);
	private static String DEFAULT_CHARSET = "UTF-8";
	private static int DEFAULT_CONNECTION_TIMEOUT = 10 * 1000;
	private static int DEFAULT_SO_TIMEOUT = 10 * 1000;
	public static String addUrl(String head, String tail) {
		if (head.endsWith("/")) {
			if (tail.startsWith("/")) {
				return head.substring(0, head.length() - 1) + tail;
			} else {
				return head + tail;
			}
		} else {
			if (tail.startsWith("/")) {
				return head + tail;
			} else {
				return head + "/" + tail;
			}
		}
	}

	/**
	 * post请求数据
	 * @param url
	 * @param params
	 * @param charset
	 * @return
	 * @throws Exception
	 */
	public synchronized static String postData(String url, JSONObject json, String charset) throws Exception {
		//构造HttpClient的实例 
		HttpClient httpClient = new HttpClient();
		//创建post方法的实例 
		PostMethod method = new PostMethod(url);
		charset=StringUtils.isBlank(charset)? DEFAULT_CHARSET:charset;
		
		((PostMethod) method).addParameter("json", json.toString());  
		HttpMethodParams httpMethodParam = method.getParams();  
		httpMethodParam.setContentCharset("UTF-8");  
		httpMethodParam.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
		String result = "";
		try {
			httpClient.executeMethod(method);// 执行postMethod 
			result=new String(method.getResponseBody(),charset);
		} catch (Exception e) {
			throw e;
		}finally{
			//释放连接 
			method.releaseConnection();
		}
		return result;
	}
	
	public synchronized static String postData(String url, Map<String,String> header,JSONObject json, String charset) throws Exception {
		//构造HttpClient的实例 
		HttpClient httpClient = new HttpClient();
		//创建post方法的实例 
		PostMethod method = new PostMethod(url);
		charset=StringUtils.isBlank(charset)? "utf-8":charset;
		
		((PostMethod) method).addParameter("cdata", json.toString());  
		HttpMethodParams httpMethodParam = method.getParams();  
		httpMethodParam.setContentCharset("UTF-8");  
		httpMethodParam.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
		// 添加请求头
		Iterator<String> iter = header.keySet().iterator();
		String key = null;
		while(iter.hasNext()) {
			key = iter.next();
			method.addRequestHeader(key,header.get(key));
		}
		String result = "";
		try {
			httpClient.executeMethod(method);// 执行postMethod 
			result=new String(method.getResponseBody(),charset);
		} catch (Exception e) {
			logger.error("HTTP以POST请求数据异常", e);
			throw e;
		}finally{
			//释放连接 
			method.releaseConnection();
		}
		return result;
	}
	
	/**
	 *  get请求数据
	 * @param url
	 * @param params
	 * @param charset
	 * @return
	 * @throws Exception
	 */
	public synchronized static String getData(String url, Map<String, String> params, String charset) throws Exception {
		final  HttpClient httpClient = new HttpClient();
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
		httpClient.getHttpConnectionManager().getParams().setSoTimeout(DEFAULT_SO_TIMEOUT);
		final GetMethod method = new GetMethod(url);
		String result = "";
		try {
			httpClient.executeMethod(method);
			charset=StringUtils.isBlank(charset)? DEFAULT_CHARSET:charset;
			result=new String(method.getResponseBody(),charset);
		} catch (Exception e) {
			logger.info("HTTP以GET请求数据异常", e);
			throw e;
		}finally{
			method.releaseConnection();
		}
		return result;
		}
}

 

转载于:https://my.oschina.net/u/3053442/blog/1555454

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值