简单的Restful工具类
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.apache.log4j.Logger;
/**
* Restful工具类
* @version 1
*/
public class RestfulUtil {
private static final Logger log = Logger.getLogger(RestfulUtil.class);
private static int SUCCESS = 200;
/**
* 执行调用restful接口
*
* @param url 接口访问地址
* @param type 访问类型:GET、POST
* @param objectParam 参数
* @return 调用restful结果
*/
public static String restfulInvoke(String url, String type, Object objectParam) {
URL targetUrl = null;
HttpURLConnection httpConnection = null;
OutputStream output = null;
InputStream in = null;
InputStreamReader isr = null;
BufferedReader br = null;
ByteArrayOutputStream baos = null;
try {
targetUrl = new URL(url);
httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setUseCaches(false);
httpConnection.setRequestMethod(type);
httpConnection.setRequestProperty("Content-Type", "application/json");
if (null != objectParam) {
String param = GsonUtil.toJson(objectParam);
output = httpConnection.getOutputStream();
output.write(param.getBytes("utf-8"));
output.flush();
}
int responseCode = httpConnection.getResponseCode();
if (SUCCESS != responseCode) {
log.error("request restful failed,HTTP error code:" + responseCode);
throw new RuntimeException("Failed : HTTP error code : " + responseCode);
}
in = httpConnection.getInputStream();
isr = new InputStreamReader(in, "utf-8");
br = new BufferedReader(isr);
baos = new ByteArrayOutputStream();
String line = "";
LineIterator iterator=new LineIterator(br);
while(iterator.hasNext())
{
line = iterator.next();
baos.write(line.getBytes());
}
baos.flush();
byte bArray[] = baos.toByteArray();
return new String(bArray);
} catch (IOException e) {
log.error(e);
return null;
} finally {
if (null != httpConnection) {
httpConnection.disconnect();
}
closeStream(output);
closeStream(in);
closeStream(isr);
closeStream(br);
closeStream(baos);
}
}
/**
* 执行调用restful接口
* @param url 接口访问地址
* @param type 访问类型:GET、POST
* @param objectParam 参数
* @return 调用restful结果
*/
public static String restfulInvoke(String url, String type, Object objectParam,String projectCode) {
URL targetUrl = null;
HttpURLConnection httpConnection = null;
OutputStream output = null;
InputStream in = null;
InputStreamReader isr = null;
BufferedReader br = null;
ByteArrayOutputStream baos = null;
try {
targetUrl = new URL(url);
httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setUseCaches(false);
httpConnection.setRequestMethod(type);
httpConnection.setRequestProperty("Content-Type", "application/json");
httpConnection.setRequestProperty("Accept-Charset", "UTF-8");
httpConnection.setRequestProperty("ProjectCode", projectCode);
if (null != objectParam) {
String param = GsonUtil.toJson(objectParam);
output = httpConnection.getOutputStream();
output.write(param.getBytes("utf-8"));
output.flush();
}
int responseCode = httpConnection.getResponseCode();
if (SUCCESS != responseCode) {
log.error("request restful failed,HTTP error code:" + responseCode);
throw new RuntimeException("Failed : HTTP error code : " + responseCode);
}
in = httpConnection.getInputStream();
isr = new InputStreamReader(in, "utf-8");
br = new BufferedReader(isr);
baos = new ByteArrayOutputStream();
String line = "";
LineIterator iterator=new LineIterator(br);
while(iterator.hasNext())
{
line = iterator.next();
baos.write(line.getBytes());
}
baos.flush();
byte bArray[] = baos.toByteArray();
return new String(bArray);
} catch (IOException e) {
log.error(e);
return null;
} finally {
if (null != httpConnection) {
httpConnection.disconnect();
}
closeStream(output);
closeStream(in);
closeStream(isr);
closeStream(br);
closeStream(baos);
}
}
/**
* 执行调用restful接口
*
* @param url 接口访问地址
* @param type 访问类型:GET、POST
* @param objectParam 参数
* @return 调用restful结果
*/
public static String restfulInvoke(String url, String type, Object objectParam,String projectCode,String projectName) {
URL targetUrl = null;
HttpURLConnection httpConnection = null;
OutputStream output = null;
InputStream in = null;
InputStreamReader isr = null;
BufferedReader br = null;
ByteArrayOutputStream baos = null;
try {
targetUrl = new URL(url);
httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setUseCaches(false);
httpConnection.setRequestMethod(type);
httpConnection.setRequestProperty("Content-Type", "application/json");
httpConnection.setRequestProperty("Accept-Charset", "UTF-8");
httpConnection.setRequestProperty("ProjectCode", projectCode);
httpConnection.setRequestProperty("ProjectName", projectName);
if (null != objectParam) {
String param = GsonUtil.toJson(objectParam);
output = httpConnection.getOutputStream();
output.write(param.getBytes("utf-8"));
output.flush();
}
int responseCode = httpConnection.getResponseCode();
if (SUCCESS != responseCode) {
log.error("request restful failed,HTTP error code:" + responseCode);
throw new RuntimeException("Failed : HTTP error code : " + responseCode);
}
in = httpConnection.getInputStream();
isr = new InputStreamReader(in, "utf-8");
br = new BufferedReader(isr);
baos = new ByteArrayOutputStream();
String line = "";
LineIterator iterator=new LineIterator(br);
while(iterator.hasNext())
{
line = iterator.next();
baos.write(line.getBytes());
}
baos.flush();
byte bArray[] = baos.toByteArray();
return new String(bArray);
} catch (IOException e) {
log.error(e);
return null;
} finally {
if (null != httpConnection) {
httpConnection.disconnect();
}
closeStream(output);
closeStream(in);
closeStream(isr);
closeStream(br);
closeStream(baos);
}
}
/**
* 调用文件下载restful接口
*
* @param url
* @param fileID
* @return 文件流
*/
public static InputStream getFileInputStream(String url, String fileID) {
URL targetUrl = null;
HttpURLConnection httpConnection = null;
InputStream in = null;
try {
targetUrl = new URL(url + "?ID=" + fileID);
httpConnection = (HttpURLConnection) targetUrl.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setUseCaches(false);
httpConnection.setRequestMethod("GET");
httpConnection.setRequestProperty("Content-Type", "application/json");
httpConnection.setRequestProperty("Accept-Charset", "UTF-8");
int responseCode = httpConnection.getResponseCode();
if (SUCCESS != responseCode) {
throw new RuntimeException("Failed : HTTP error code : " + responseCode);
}
in = httpConnection.getInputStream();
} catch (Exception e) {
log.error(e);
}
return in;
}
/**
* 根据url下载一个文件,需要提供文件路径,谁调用谁删除
* @param url
* @param fileID
* @param filepath
* @return
*/
public static File getFileInputStream(String url, String fileID, String filepath) {
URL targetUrl = null;
try {
targetUrl = new URL(url + "?ID=" + fileID);
String parent = filepath.substring(0, filepath.lastIndexOf("/"));
File dir = new File(parent);
if (!dir.exists()) {
if(!dir.mkdirs()){
throw new Exception("文件夹创建失败!");
}
}
File file = new File(filepath);
FileUtils.copyURLToFile(targetUrl, file);
return file;
} catch (Exception e) {
log.error(e);
return null;
}
}
/**
* 关闭流
* @param stream 待关闭的流
*/
public static void closeStream(Closeable stream) {
if (null != stream) {
try {
stream.close();
} catch (IOException e) {
log.error("close stream error: ", e);
}
}
}
// @Test
// public void test1() {
// // "http://127.0.0.1:8090/Download",
// // "e5ab2e9","zip/Temp/40ab9/temp.zip"
// File file = getFileInputStream("http://127.0.0.1:8080/Download", "85974fd70", "zip/Temp/85974fd70/temp.zip");
// System.out.println(file.getAbsolutePath());
// }
}
简单的Restful工具类的更多相关文章
- java使用注解和反射打造一个简单的jdbc工具类
a simple jdbc tools 如有转载和引用,请注明出处,谢谢 1. 定义我们需要的注解 要想实现对数据库的操作,我们必须知道数据表名以及表中的字段名称以及类型,正如hibernate 使用 ...
- iOS开发--换肤简单实现以及工具类的抽取
一.根据美工提供的图片,可以有两种换肤的方案. <1>美工提供图片的类型一: <2>美工提供图片的类型二:这种分了文件夹文件名都一样的情况,拖入项目后最后用真实文件夹(蓝色文件 ...
- Swift - 简单封装一个工具类模板
创建模板类(封装一个类) 例1:新建一个名字叫做 Product 的类 Product.swift File 的内容 class Product { var name: String var desc ...
- 一个简单的Hibernate工具类HibernateUtil
HibernateUtil package com.wj.app.util; import org.hibernate.Session; import org.hibernate.SessionFac ...
- 简单的redis工具类
import java.util.Arrays; import java.util.List;import java.util.Set; import org.apache.commons.lang. ...
- JAVA简单精确计算工具类
1 public class ArithUtil { 2 3 // 默认除法运算精度 4 private static final int DEF_DIV_SCALE = 10; 5 6 privat ...
- Java学习笔记43(打印流、IO流工具类简单介绍)
打印流: 有两个类:PrintStream,PrintWriter类,两个类的方法一致,区别在于构造器 PrintStream:构造方法:接收File类型,接收字符串文件名,接收字节输出流(Outpu ...
- JDK中工具类的使用
JDK中内置了很多常用的工具类,且多以“s”结尾,如:集合工具类Collections,数组工具类Arrays,对象工具类Objects,文件工具类Files,路径工具类Paths,数学工具类Math ...
- 基于JavaMail开发邮件发送器工具类
基于JavaMail开发邮件发送器工具类 在开发当中肯定会碰到利用Java调用邮件服务器的服务发送邮件的情况,比如账号激活.找回密码等功能.本人之前也碰到多次这样需求,为此特意将功能封装成一个简单易用 ...
随机推荐
- [EffectiveC++]item43:学习处理模板化基类内的名称
- npm install --save 和 --save-dev的区别
--save 会把依赖包名称添加到 package.json 文件 "dependencies" 键下--save-dev 则添加到 package.json 文件 "d ...
- casperjs,phantomjs,slimerjs and spooky
1.casperjs http://casperjs.org/ CasperJS is a navigation scripting & testing utility for Phantom ...
- BZOJ1001: [BeiJing2006]狼抓兔子【最短路+对偶图】
题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=1001 1001: [BeiJing2006]狼抓兔子 Time Limit: 15 Se ...
- Python 3 与 Javascript escape 传输确保数据正确方法和中文乱码解决方案
注意:现在已不推荐 escape 函数,推荐使用 encodeURIComponent 函数,其中方法更简单,只需进行URL解码即可. 当然了,如下文章解决方案一样可行. 前几天用Python的Bo ...
- 【Agile123】Automated Test in Agile
https://www.infoq.com/articles/thoughts-on-test-automation-in-agile Start Small Balance the cost vs. ...
- 联通营业厅API 获取个人信息
string newValue = base.Request["tel"]; string newValue2 = base.Request["pwd"]; s ...
- --provider=docker时出现的问题
Vagrantfile类似: Vagrant.configure(") do |config| config.vm.box = "hashicorp/precise64" ...
- Docker实战(三)之访问Docker仓库
仓库是集中存放镜像的地方,分为公共仓库和私有仓库.一个容易与之混肴的概念是注册服务器.实际上注册服务器是存放仓库的具体服务器,一个注册服务器上可以有多个仓库,而每个仓库下面可以有多个镜像.从这方面来说 ...
- B. Vile Grasshoppers
http://codeforces.com/problemset/problem/937/B The weather is fine today and hence it's high time to ...