JAVA httpClient get请求及接收示例代码

本文介绍了如何使用JAVA的HttpClient库进行GET请求,分别展示了HttpClient4.5和3.1版本的示例代码,同时讲解了如何接收数据。

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

 1、java原生httpClient4.5 get请求

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

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class SendHttp {
	
	/**
	 * java原生httpClient4.5 get请求
	 */
	@SuppressWarnings("unchecked")
	public static Map<String, Object> sendGet(String sendUrl) {
		Map<String, Object> mres = new HashMap<String, Object>();
		// 默认配置创建一个httpClient实例
		CloseableHttpClient httpClient = HttpClients.createDefault();
		// 创建httpGet远程连接实例
		HttpGet httpGet = new HttpGet(sendUrl);
		// 设置配置请求参数
		RequestConfig requestConfig = RequestConfig.custom()
				.setConnectTimeout(35000)// 连接主机服务超时时间
				.setConnectionRequestTimeout(35000)// 请求超时时间
				.setSocketTimeout(60000)// 数据读取超时时间
				.build();
		// 为httpGet实例设置配置
		httpGet.setConfig(requestConfig);
		try {
			// 执行get请求得到返回对象
			CloseableHttpResponse response = httpClient.execute(httpGet);
			// 通过返回对象获取返回数据
			HttpEntity entity = response.getEntity();
			// 通过EntityUtils中的toString方法将结果转换为字符串
			String result = EntityUtils.toString(entity, "UTF-8");
			mres = (Map<String, Object>) JSONObject.toBean(JSONObject.fromObject(result), Map.class);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			if (null != httpClient) {
				try {
					httpClient.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return mres;
        }
        //测试
        public static void main(String[] args) throws Exception { 
            StringBuilder builder = new StringBuilder();
            builder.append("http://localhost:8080/sm/test/getGetData.form");
            builder.append("?user_name=lanqinger");
            builder.append("&real_name=蓝卿儿");
            Map<String,Object> resultGet = sendGet(builder.toString());
            System.out.println(resultGet);
      }
} 

2、java原生httpClient3.1 get请求
 

        /**
         * java原生httpClient3.1 get请求
         */
        @SuppressWarnings("unchecked")
	public static Map<String, Object> sendGet2(String sendUrl) {
		Map<String, Object> mres = new HashMap<String, Object>();
		HttpClient httpClient = new HttpClient();
		GetMethod getMethod = new GetMethod(sendUrl);
		String responseMsg = "";
		// 设置get请求超时为6000毫秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 6000);
		// 使用系统系统的默认的恢复策略
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
		try {
			// 3.执行getMethod,调用http接口
			httpClient.executeMethod(getMethod);
			// 4.读取内容
			byte[] responseBody = getMethod.getResponseBody();
			// 5.处理返回的内容
			responseMsg = new String(responseBody, "UTF-8");
			mres = (Map<String, Object>) JSONObject.toBean(JSONObject.fromObject(responseMsg), Map.class);
		} catch (Exception e) {
			e.printStackTrace();
			mres.put("status", "9999");
			mres.put("message", "请求处理异常"+e.getMessage());
		} finally {
			// 6.释放连接
			getMethod.releaseConnection();
		}
		return mres;
	}

接收数据:

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

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lhm.service.UserInfoService;
import com.lhm.util.API;
import com.lhm.value.UserInfoPage;

@Controller
@RequestMapping("/test")
public class TestController {
	private static Logger log = Logger.getLogger(TestController.class);

	@Resource
	private UserInfoService userInfoService;
	
	@RequestMapping(value="/getGetData.form", produces="application/json;charset=UTF-8")
	@ResponseBody
	public Object getGetData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String userName = request.getParameter("user_name");
		String realName = request.getParameter("real_name");
		UserInfoPage userInfoPage = new UserInfoPage();
		userInfoPage.setUser_name(userName);
		userInfoPage.setReal_name(realName);
		userInfoPage.setCurrentPage(1);
		userInfoPage.setPageSize(10);
		List<Map<String, Object>> list = userInfoService.listUsersMap(userInfoPage);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", "1");
		map.put("total", list.size());
		map.put("message", "执行成功!");
		return JSONObject.fromObject(map).toString();
	}
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值