Java实现HttpGet和HttpPost请求
2024-09-05 07:17:51
maven引入JSON处理jar
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
maven引入数据源配置,用于log记录
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>
HttpGet和HttpPost请求
import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLOutput;
import java.util.Map;
public class ReqHttp {
private static final Log logger = LogFactory.getLog(ReqHttp.class);
public static JSONObject get(String reqUrl,Map<String,Object> paramMap) throws IOException {
StringBuffer param =new StringBuffer();
for(Map.Entry<String,Object> en:paramMap.entrySet()){
param.append(en.getKey()+"="+en.getValue()+"&");
}
BufferedReader responseReader = null;
String urlPath = ReqStatUrl.DOMAIN_URL + reqUrl+"?"+param.toString();
try {
//建立连接
URL url = new URL(urlPath);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
//设置参数
httpConn.setDoOutput(true); //需要输出
httpConn.setDoInput(true); //需要输入
httpConn.setUseCaches(false); //不允许缓存
httpConn.setRequestMethod("GET"); //设置GET方式连接
httpConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");//流信息 可以传输图片音频等信息
httpConn.setRequestProperty("Charset", "UTF-8");
httpConn.setRequestProperty("entCode", ReqStatHeader.entCode);//参数常量
httpConn.setRequestProperty("tokenId", ReqStatHeader.tokenId);//参数常量
httpConn.setConnectTimeout(30000);
httpConn.setReadTimeout(30000);
//连接,也可以不用明文connect,使用下面的httpConn.getOutputStream()会自动connect
httpConn.connect();
//获得响应状态
int resultCode = httpConn.getResponseCode();
if (HttpURLConnection.HTTP_OK == resultCode) {
StringBuffer sb = new StringBuffer();
String readLine = new String();
responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
while ((readLine = responseReader.readLine()) != null) {
sb.append(readLine).append("\n");
}
System.out.println(sb.toString());
logger.info(sb.toString());
JSONObject json = JSONObject.parseObject(sb.toString(),JSONObject.class);
return json;
}
} catch (Exception e) {
logger.error("get 请求失败:"+urlPath);
} finally {
if(null != responseReader) responseReader.close();
}
return null;
}
public static JSONObject post(String reqUrl,Map<String,Object> paramMap) throws Exception {
BufferedReader responseReader = null;
OutputStream dos= null;
String urlPath = ReqStatUrl.DOMAIN_URL + reqUrl;
try {
//建立连接
URL url = new URL(urlPath);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
//设置参数
httpConn.setDoOutput(true); //需要输出
httpConn.setDoInput(true); //需要输入
httpConn.setUseCaches(false); //不允许缓存
httpConn.setRequestMethod("POST"); //设置POST方式连接
httpConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");//流信息 可以传输图片音频等信息
httpConn.setRequestProperty("Charset", "UTF-8");
httpConn.setRequestProperty("entCode", ReqStatHeader.entCode);//参数常量
httpConn.setRequestProperty("tokenId", ReqStatHeader.tokenId);//参数常量
httpConn.setConnectTimeout(30000);
httpConn.setReadTimeout(30000);
//连接,也可以不用明文connect,使用下面的httpConn.getOutputStream()会自动connect
httpConn.connect();
//建立输入流,向指向的URL传入参数
byte[] jsonObject = JSONObject.toJSONBytes(paramMap);
dos = httpConn.getOutputStream();
dos.write(jsonObject);
dos.flush();
//获得响应状态
int resultCode = httpConn.getResponseCode();
if (HttpURLConnection.HTTP_OK == resultCode) {
StringBuffer sb = new StringBuffer();
String readLine = new String();
responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
while ((readLine = responseReader.readLine()) != null) {
sb.append(readLine).append("\n");
}
// System.out.println(sb.toString());
logger.info(sb.toString());
JSONObject json = JSONObject.parseObject(sb.toString(),JSONObject.class);
return json;
}
} catch (Exception e) {
logger.error("get 请求失败:"+urlPath);
} finally {
if(null != responseReader) responseReader.close();
if(null != dos) dos.close();
}
return null;
}
}
常用参数静态引用
public class ReqStatHeader {
public static String entCode="";
public static String tokenId="";
public static String appCode = "";
public static String secret = "";
}
常用API地址静态引用,便于地址维护
public class ReqStatUrl {
public static String DOMAIN_URL = "https://www.xxxxx.com/xxxx/xxxx";
/**
* 认证
*/
public static String AUTH_LOGIN = "/auth/login";
/**
*获取已提交对私报销单据
*/
public static String REPORT_PERSONAL_SUBMITTED= "/report/personal/submitted";
/**
* 获取已提交对私报销单据详情
*/
public static String REPORT_PERSONAL_DETAIL = "/report/personal/detail";
}
最新文章
- Spring配置文件中别名的使用
- MySQL常用语句
- 剑指offer—第三章高质量代码(数值的整数次方)
- linux入门教程(四) 初步进入linux世界
- [Javascript] Create an Array concatAll method
- 简单学C——第一天
- GO中的数组切片
- maven project module 依赖项目创建 ---转
- SVN报Previous operation has not finished; run 'cleanup'&
- Java之Iterator
- JDK动态代理深入理解分析并手写简易JDK动态代理(上)
- IPC$概念及入侵方式研究
- 论YUV422(YUYV)与YUV420相互转换
- 《CSS世界》读书笔记(七)
- Hibernate3.0配置
- SQL Server 2017数据库服务和SSMS图形化工具的的安装
- synchronized的一些记录
- UGUI之Scrollbar使用
- 采用PowerDesigner 设计数据库
- [C#]C#彩色扭曲验证码
热门文章
- [loj3524]钥匙
- [tc14634]ExtremeSpanningTrees
- 微信和QQ这么多群,该如何管理好友关系?
- Spring Cloud Gateway修改请求和响应body的内容
- Insights直播回顾,对话专家,HMS Core 6创新能力解读
- 痞子衡嵌入式:深扒IAR启动函数流程之段初始化实现中可用的压缩选项
- SpringBoot引入第三方jar的Bean的三种方式
- 模数不超过 long long 范围时的快速乘
- P3722 [AH2017/HNOI2017]影魔(单调栈+扫描线+线段树)
- Codeforces 582D - Number of Binominal Coefficients(Kummer 定理+数位 dp)