Java http请求工具类
该工具类可以调用POST请求或者Get请求,参数以Map的方式传入,支持获获取返回值,返回值接收类型为String
HttpRequestUtil.java
package com.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
/**
* 用于模拟HTTP请求中GET/POST方式
*
* @author https://www.mojxtang.club/
* @date 2017年8月24日
*/
public class HttpRequestUtil {
/**
* 发送GET请求
*
* @param url 目的地址
* @param parameters 请求参数,Map类型。
* @return 远程响应结果
*/
public static String sendGet(String url, Map<String, String> parameters) {
String result = "";
BufferedReader in = null;// 读取响应输入流
StringBuffer sb = new StringBuffer();// 存储参数
String params = "";// 编码之后的参数
try {
// 编码请求参数
if (parameters.size() == 1) {
for (String name : parameters.keySet()) {
sb.append(name).append("=").append(java.net.URLEncoder.encode(parameters.get(name), "UTF-8"));
}
params = sb.toString();
} else {
for (String name : parameters.keySet()) {
sb.append(name).append("=").append(java.net.URLEncoder.encode(parameters.get(name), "UTF-8"))
.append("&");
}
String temp_params = sb.toString();
params = temp_params.substring(0, temp_params.length() - 1);
}
String full_url = url + "?" + params;
System.out.println(full_url);
// 创建URL对象
java.net.URL connURL = new java.net.URL(full_url);
// 打开URL连接
java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL.openConnection();
// 设置通用属性
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
// 建立实际的连接
httpConn.connect();
// 响应头部获取
Map<String, List<String>> headers = httpConn.getHeaderFields();
// 遍历所有的响应头字段
for (String key : headers.keySet()) {
System.out.println(key + "\t:\t" + headers.get(key));
}
// 定义BufferedReader输入流来读取URL的响应,并设置编码方式
in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
String line;
// 读取返回的内容
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* 发送POST请求
*
* @param url 目的地址
* @param parameters 请求参数,Map类型。
* @return 远程响应结果
*/
public static String sendPost(String url, Map<String, String> parameters) {
String result = "";// 返回的结果
BufferedReader in = null;// 读取响应输入流
PrintWriter out = null;
StringBuffer sb = new StringBuffer();// 处理请求参数
String params = "";// 编码之后的参数
try {
// 编码请求参数
if (parameters.size() == 1) {
for (String name : parameters.keySet()) {
sb.append(name).append("=").append(java.net.URLEncoder.encode(parameters.get(name), "UTF-8"));
}
params = sb.toString();
} else {
for (String name : parameters.keySet()) {
sb.append(name).append("=").append(java.net.URLEncoder.encode(parameters.get(name), "UTF-8"))
.append("&");
}
String temp_params = sb.toString();
params = temp_params.substring(0, temp_params.length() - 1);
}
// 创建URL对象
java.net.URL connURL = new java.net.URL(url);
// 打开URL连接
java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL.openConnection();
// 设置通用属性
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
// 设置POST方式
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
// 获取HttpURLConnection对象对应的输出流
out = new PrintWriter(httpConn.getOutputStream());
// 发送请求参数
out.write(params);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应,设置编码方式
in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
String line;
// 读取返回的内容
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
public static String sendPostTest(String url, JSONObject json) {
String result = "";// 返回的结果
BufferedReader in = null;// 读取响应输入流
PrintWriter out = null;
String params = "";// 编码之后的参数
try {
// 编码请求参数
params = json.toString();
// 创建URL对象
java.net.URL connURL = new java.net.URL(url);
// 打开URL连接
java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL.openConnection();
// 设置通用属性
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Connection", "Keep-Alive");
httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
// 设置POST方式
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
// 获取HttpURLConnection对象对应的输出流
out = new PrintWriter(httpConn.getOutputStream());
// 发送请求参数
out.write(params);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应,设置编码方式
in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
String line;
// 读取返回的内容
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
Java http请求工具类的更多相关文章
- Http请求工具类(Java原生Form+Json)
package com.tzx.cc.common.constant.util; import java.io.IOException; import java.io.InputStream; imp ...
- java模板模式项目中使用--封装一个http请求工具类
需要调用http接口的代码继承FundHttpTemplate类,重写getParamData方法,在getParamDate里写调用逻辑. 模板: package com.crb.ocms.fund ...
- java jdk原生的http请求工具类
package com.base; import java.io.IOException; import java.io.InputStream; import java.io.InputStream ...
- Http、Https请求工具类
最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...
- 微信https请求工具类
工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...
- HttpTool.java(在java tool util工具类中已存在) 暂保留
HttpTool.java 该类为java源生态的http 请求工具,不依赖第三方jar包 ,即插即用. package kingtool; import java.io.BufferedReader ...
- java格式处理工具类
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOExceptio ...
- 远程Get,Post请求工具类
1.远程请求工具类 import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...
- Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类
Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...
随机推荐
- css自定义鼠标
亲们支持我的新博客哦==>地址(以后更新会尽量在新博客更新,欢迎大家访问加入我的后宫w) ) css自定义鼠标 效果展示==> 注意: 1.支持jpg/png/ico格式的展示鼠标格式,为 ...
- SQL server约束
约束的概念:确保在列中输入有效的值并维护表之间的关系. Primary key约束 功能:primary key(主键约束),一个表中只能有一个,不能有空值,不能有重复值. 创建表时定义约束:字段名 ...
- c# 值类型与引用类型的传参(形参与实参)
形参是指被调用方法中的参数 实参是指传递给方法的参数 (1)值类型传参是按值传递 值类型传参,形参接受到的是实参的一个副本,即形参发生变化,实参不会发生任何变化 (2)引用类型参数按值传递 当参数传递 ...
- Suricata在ubuntu14.04环境下安装
简介 Suricata是一款高性能的网络IDS.IPS和网络安全监控引擎.它是由the Open Information Security Foundation开发,是一款开源的系统,现在的NIDS领 ...
- spring boot 自定义视图路径
boot 自定义访问视图路径 . 配置文件 目录结构 启动类: html页面 访问: 覆盖boot默认路径引用. 如果没有重新配置,则在pom引用模板. 修改配置文件. 注意一定要编译工程
- java.net.BindException: 地址已在使用 (Bind failed)
java.net.BindException: 地址已在使用,是因为端口被占用,出现在启动服务的时候 报错如截图 报错显示 10062端口被占用冲突 执行netstat -alnp | grep 10 ...
- spring 之 lookup-method & replaced-method II
显然, lookup-method 的name 对应的方法 是可以有方法参数的, 但是, 我发现, 参数无法传递, 传过去的参数好像被丢入了黑洞一般... 非常奇怪. lookup-method 的n ...
- <转载> GIT 操作小结 http://www.cnblogs.com/-ding/p/6008096.html
参考: http://www.cnblogs.com/zyf-zhaoyafei/p/4486220.html 作者:万境绝尘 转载请注明出处:http://blog.csdn.net/shulian ...
- pycharm中查找替换妙用
1.二行空格变一行(转载https://www.cnblogs.com/dreamfine/p/7760575.html) 网上COPY的代码,经常多出一个空行,不用一行行删除了,用替换功能吧,查找 ...
- PHP Composer 包管理器的安装和使用
一,包管理器的安装 01,首先确定 php 命令能够全局使用,要是不能请修改环境变量 02,使用 curl 命令安装 => curl -sS http://install.phpcomposer ...