该工具类可以调用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请求工具类的更多相关文章

  1. Http请求工具类(Java原生Form+Json)

    package com.tzx.cc.common.constant.util; import java.io.IOException; import java.io.InputStream; imp ...

  2. java模板模式项目中使用--封装一个http请求工具类

    需要调用http接口的代码继承FundHttpTemplate类,重写getParamData方法,在getParamDate里写调用逻辑. 模板: package com.crb.ocms.fund ...

  3. java jdk原生的http请求工具类

    package com.base; import java.io.IOException; import java.io.InputStream; import java.io.InputStream ...

  4. Http、Https请求工具类

    最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...

  5. 微信https请求工具类

    工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...

  6. HttpTool.java(在java tool util工具类中已存在) 暂保留

    HttpTool.java 该类为java源生态的http 请求工具,不依赖第三方jar包 ,即插即用. package kingtool; import java.io.BufferedReader ...

  7. java格式处理工具类

    import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOExceptio ...

  8. 远程Get,Post请求工具类

    1.远程请求工具类   import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...

  9. Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类

    Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...

随机推荐

  1. SQL server 数据库的数据完整性

    存储在数据库中的所有数据值均正确的状态.如果数据库中存储有不正确的数据值,则该数据库称为已丧失数据完整性. 详细释义 数据库中的数据是从外界输入的,而数据的输入由于种种原因,会发生输入无效或 错误信息 ...

  2. Python-requests设置请求的超时时间

    使用timeout 参数可以设定等待连接的秒数,如果等待超时,Requests会抛出异常 >>> requests.get('http://github.com', timeout= ...

  3. html-prepend

    $('.classDiv').prepend('<span>添加</span>')

  4. 基于canvas的电子始终

    //code <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <ti ...

  5. hadoop-eclipse插件编译及windows下运行wordcount项目

    参考文章:http://www.360doc.com/content/16/0227/18/10529016_537828949.shtml, 配置修改:http://blog.csdn.net/lo ...

  6. js 在光标位置插入内容

    原文:https://blog.csdn.net/smartsmile2012/article/details/53642082 createDocumentFragment()用法: https:/ ...

  7. WPF 透明窗体

    窗体属性中设置:Background="Transparent" AllowsTransparency="True" WindowStyle="Non ...

  8. c#从基础学起string.Join(",", keys.ToArray())

    总感觉自己工作6年了,经验丰富.直到近期报了一个.net进阶班才知道.我还差得很远.就拿string.join对比 我的代码: public static int InsertModel<T&g ...

  9. day06-单表查询

    1.单表查询的语法 SELECT 字段1,字段2... FROM 表名 WHERE 条件 GROUP BY field HAVING 筛选 ORDER BY field LIMIT 限制条数 2.关键 ...

  10. php中显示数组与对象的实现代码

    1. 使用 print_r ( $array/$var ) print 是打印的意思,而r则取自Array的单词,那么该函数的功能就是打印数组内容,它既可以打印数组内容,也可以打印普通的变量. pri ...