java连接外部接口获取数据工具类
package com.yqzj.util;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
public class HttpRequestUtil {
/** 日志 */
private static Logger log = LogManager.getLogger(HttpRequestUtil.class);
/**
* 向指定URL发送GET方法的请求
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @param url
* 发送请求的URL
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url) {
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("contentType", "UTF-8");
// 建立实际的连接
connection.connect();
// 遍历所有的响应头字段
// for (String key : map.keySet()) {
// System.out.println(key + "--->" + map.get(key));
// }
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
// System.out.println("发送GET请求出现异常!" + e);
result = new StringBuilder("{\"resCode\":\"1\",\"errCode\":\"1001\",\"resData\":\"\"}");
e.printStackTrace();
log.error("远程服务未开启", e);
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result.toString();
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("contentType", "UTF-8");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
// System.out.println("发送 POST 请求出现异常!" + e);
result = new StringBuilder("{\"resCode\":\"1\",\"errCode\":\"1001\",\"resData\":\"\"}");
e.printStackTrace();
log.error("远程服务未开启", e);
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result.toString();
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendFile(String url, String param,
BufferedInputStream bInputStream) {
BufferedOutputStream out = null;
BufferedReader in = null;
StringBuilder result = new StringBuilder();
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setRequestProperty("contentType", "multipart/form-data");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 发送参数
StringBuffer sb = new StringBuffer();
sb = sb.append(param);
byte[] paramData = sb.toString().getBytes();
// System.out.println(paramData.length);
out = new BufferedOutputStream(conn.getOutputStream());
out.write(paramData);
if (bInputStream != null) {
byte[] data = new byte[2048];
while (bInputStream.read(data) != -1) {
out.write(data);
}
}
out.flush();
// flush输出流的缓冲
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
// System.out.println("发送 POST 请求出现异常!" + e);
result = new StringBuilder("{\"resCode\":\"1\",\"errCode\":\"1001\",\"resData\":\"\"}");
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (bInputStream != null) {
bInputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result.toString();
}
}
java连接外部接口获取数据工具类的更多相关文章
- java从Swagger Api接口获取数据工具类
- java中excel导入\导出工具类
1.导入工具 package com.linrain.jcs.test; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import ...
- Java 操作Redis封装RedisTemplate工具类
package com.example.redisdistlock.util; import org.springframework.beans.factory.annotation.Autowire ...
- 系统获取 IP 工具类
系统获取 IP 工具类 import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterf ...
- Spring获取bean工具类,可用于在线程里面获取bean
Spring获取bean工具类,可用于在线程里面获取bean import java.util.Locale; import org.springframework.beans.BeansExcept ...
- java中的Arrays这个工具类你真的会用吗
Java源码系列三-工具类Arrays 今天分享java的源码的第三弹,Arrays这个工具类的源码.因为近期在复习数据结构,了解到Arrays里面的排序算法和二分查找等的实现,收益匪浅,决定研读 ...
- Java操作文件夹的工具类
Java操作文件夹的工具类 import java.io.File; public class DeleteDirectory { /** * 删除单个文件 * @param fileName 要删除 ...
- Java汉字转成汉语拼音工具类
Java汉字转成汉语拼音工具类,需要用到pinyin4j.jar包. import net.sourceforge.pinyin4j.PinyinHelper; import net.sourcefo ...
- java中定义一个CloneUtil 工具类
其实所有的java对象都可以具备克隆能力,只是因为在基础类Object中被设定成了一个保留方法(protected),要想真正拥有克隆的能力, 就需要实现Cloneable接口,重写clone方法.通 ...
随机推荐
- iOS基础——通过案例学知识之xib、plist、mvc
透过案例学习xib的使用.plist的使用.mvc在iOS的使用,今天要做的案例效果图 1.xib和nib xib文件可以被XCode编译成nib文件,xib文件本质上是一个xml文件,而nib文件就 ...
- VUE.js入门学习(1)-起步
1.hello world <div id="app">{{content}}</div>var app = new Vue({ el:'#app', da ...
- POJ 1459:Power Network 能源网络
Power Network Time Limit: 2000MS Memory Limit: 32768K Total Submissions: 25414 Accepted: 13247 D ...
- 18 11 27 高级的服务器连接 epoll
---恢复内容开始--- 之前的 http 服务器 都是采用 轮询的方式(就像 厨师挨个问谁饿了好做饭 一样 ) 而 epoll 用着高级的 方式 事件通知 (直接问谁饿了) 同时还和 计 ...
- input只允许输入数字,并且小数点后保留4位
<input type="text" value="" name="should_send_num" id="should_ ...
- JVM探秘:jstat查看JVM统计信息
本系列笔记主要基于<深入理解Java虚拟机:JVM高级特性与最佳实践 第2版>,是这本书的读书笔记. jstat命令用来查看JVM统计信息,可以查看类加载信息.垃圾收集的信息.JIT编译信 ...
- 解决XML警告"No grammar constraints (DTD or XML Schema) referenced in the document"
解决办法: 顶部有这两行信息即可解决警告: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE ...
- Java 关于md5加密
package com.mi.util; /** * md5+salt 长度为32的加密 * @author admin * */ public class MD5 { public static v ...
- 寒假day09
今天看了论文的结构,定下了毕设论文的框架,刷了剑指offer的部分算法题.
- jupyter notebook 安装配置使用,+目录插件安装
1.安装 pip3 install jupyter 2.配置 2.1. 生成一个 notebook 配置文件 jupyter notebook --generate-config /root/.jup ...