首页 > 编程语言 >Java Http Get Post 请求工具类

Java Http Get Post 请求工具类

时间:2024-03-11 12:11:58浏览次数:31  
标签:Java Get http param Http paramMap apache import response

import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
* Http工具类
*/
public class HttpClientUtil {

static final int TIMEOUT_MSEC = 5 * 1000;

/**
* 发送GET方式请求
* @param url
* @param paramMap
* @return
*/
public static String doGet(String url,Map<String,String> paramMap){
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();

String result = "";
CloseableHttpResponse response = null;

try{
URIBuilder builder = new URIBuilder(url);
if(paramMap != null){
for (String key : paramMap.keySet()) {
builder.addParameter(key,paramMap.get(key));
}
}
URI uri = builder.build();

//创建GET请求
HttpGet httpGet = new HttpGet(uri);

//发送请求
response = httpClient.execute(httpGet);

//判断响应状态
if(response.getStatusLine().getStatusCode() == 200){
result = EntityUtils.toString(response.getEntity(),"UTF-8");
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return result;
}

/**
* 发送POST方式请求
* @param url
* @param paramMap
* @return
* @throws IOException
*/
public static String doPost(String url, Map<String, String> paramMap) throws IOException {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";

try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);

// 创建参数列表
if (paramMap != null) {
List<NameValuePair> paramList = new ArrayList();
for (Map.Entry<String, String> param : paramMap.entrySet()) {
paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}

httpPost.setConfig(builderRequestConfig());

// 执行http请求
response = httpClient.execute(httpPost);

resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
throw e;
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return resultString;
}

/**
* 发送POST方式请求
* @param url
* @param paramMap
* @return
* @throws IOException
*/
public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";

try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);

if (paramMap != null) {
//构造json格式数据
JSONObject jsonObject = new JSONObject();
for (Map.Entry<String, String> param : paramMap.entrySet()) {
jsonObject.put(param.getKey(),param.getValue());
}
StringEntity entity = new StringEntity(jsonObject.toString(),"utf-8");
//设置请求编码
entity.setContentEncoding("utf-8");
//设置数据类型
entity.setContentType("application/json");
httpPost.setEntity(entity);
}

httpPost.setConfig(builderRequestConfig());

// 执行http请求
response = httpClient.execute(httpPost);

resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
throw e;
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return resultString;
}
private static RequestConfig builderRequestConfig() {
return RequestConfig.custom()
.setConnectTimeout(TIMEOUT_MSEC)
.setConnectionRequestTimeout(TIMEOUT_MSEC)
.setSocketTimeout(TIMEOUT_MSEC).build();
}

}

标签:Java,Get,http,param,Http,paramMap,apache,import,response
From: https://www.cnblogs.com/Lee597/p/18065796

相关文章

  • default在java中的用法 java里default
    介绍default是在java8中引入的关键字,也可称为Virtualextensionmethods——虚拟扩展方法。是指,在接口内部包含了一些默认的方法实现(也就是接口中可以包含方法体,这打破了Java之前版本对接口的语法限制),从而使得接口在进行扩展的时候,不会破坏与接口相关的实现类代码。为什么需要这......
  • Java 对接Zabbix获取主机监控+告警数据
    1.Java对接ZabbixAPI前提准备  zabbix对接文档地址: https://www.zabbix.com/documentation/6.4/zh/manual/api对接ZabbixAPI接口需要针对对接的用户授予对应的API权限,如下图所示 使用超管账户登录zabbix 用户--->用户,查看用户列表      点击对接......
  • 狂神说Java——Mybatis学习笔记
    前言:配合狂神老师的教学视频使用效果更佳:https://www.bilibili.com/video/BV1NE411Q7Nx/?spm_id_from=333.1007.top_right_bar_window_custom_collection.content.click&vd_source=4c3c519d33c113799489c7417a0a4c0e1、简介环境说明:jdk8+MySQL5.7.19maven-3.6.......
  • 深入浅出Java多线程(十):CAS
    引言大家好,我是你们的老伙计秀才!今天带来的是[深入浅出Java多线程]系列的第十篇内容:CAS。大家觉得有用请点赞,喜欢请关注!秀才在此谢过大家了!!!在多线程编程中,对共享资源的安全访问和同步控制是至关重要的。传统的锁机制,如synchronized关键字和ReentrantLock等,能够有效防止多个线程......
  • Java.CompletableFuture使用
    使用CompletableFuture替代Thread+Runnable解决Thread+Runnable没有返回值、串行化和组合任务问题1、CompletableFuture.runAsync异步没有返回值需要传入一个线程池publicstaticExecutorServiceexecutor=Executors.newFixedThreadPool(10);CompletableFuture.runAsync((......
  • java时间操作
    publicstaticvoidmain(String[]args){LocalDateTimetime=LocalDateTime.of(2022,11,30,6,6,6);DateTimeFormatterof=DateTimeFormatter.ofPattern("yyyy-MM-ddHH:mm:ss");StringdateTime=time.format(of);Syste......
  • Vue项目中封装axios统一管理http请求
    <divid="content_views"class="markdown_viewsprism-tomorrow-night"><svgxmlns="http://www.w3.org/2000/svg"style="display:none;"><pathstroke-lineca......
  • JAVA注解的总结及其作用
    #一、@component标注一个类为Spring容器的Bean,(把普通pojo实例化到spring容器中,相当于配置文件中的<beanid=""class=""/>)。将其扫描注入到Spring容器,注入成Bean#二、@ServerEndpoint(value="/server/{username}")@ServerEndpoint注解用于将一个Java类标记为WebSocket端点,指......
  • Java面试必考题之线程的生命周期,结合源码,透彻讲解!
    写在开头在前面的几篇博客里,我们学习了Java的多线程,包括线程的作用、创建方式、重要性等,那么今天我们就要正式踏入线程,去学习更加深层次的知识点了。第一个需要学的就是线程的生命周期,也可以将之理解为线程的几种状态,以及互相之间的切换,这几乎是Java多线程的面试必考题,每一年都......
  • vs2019单独重新安装python37_64失败解决办法(bilibili上我最早写的是https://www.bilib
    上个周末的时候,我发现用vs2019编写python的时候。代码高亮出现了奇怪的问题,进入解决方案的时候,print还是蓝色的,但是过了几秒钟后就变为黑色了,因此在最开始的时候我试图通过换一个皮肤和在管理扩展里面找扩展来解决,但是还是有相关问题。于是到vs2019对应的python文件夹找问题,目录是......