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工具类的更多相关文章

  1. java使用注解和反射打造一个简单的jdbc工具类

    a simple jdbc tools 如有转载和引用,请注明出处,谢谢 1. 定义我们需要的注解 要想实现对数据库的操作,我们必须知道数据表名以及表中的字段名称以及类型,正如hibernate 使用 ...

  2. iOS开发--换肤简单实现以及工具类的抽取

    一.根据美工提供的图片,可以有两种换肤的方案. <1>美工提供图片的类型一: <2>美工提供图片的类型二:这种分了文件夹文件名都一样的情况,拖入项目后最后用真实文件夹(蓝色文件 ...

  3. Swift - 简单封装一个工具类模板

    创建模板类(封装一个类) 例1:新建一个名字叫做 Product 的类 Product.swift File 的内容 class Product { var name: String var desc ...

  4. 一个简单的Hibernate工具类HibernateUtil

    HibernateUtil package com.wj.app.util; import org.hibernate.Session; import org.hibernate.SessionFac ...

  5. 简单的redis工具类

    import java.util.Arrays; import java.util.List;import java.util.Set; import org.apache.commons.lang. ...

  6. JAVA简单精确计算工具类

    1 public class ArithUtil { 2 3 // 默认除法运算精度 4 private static final int DEF_DIV_SCALE = 10; 5 6 privat ...

  7. Java学习笔记43(打印流、IO流工具类简单介绍)

    打印流: 有两个类:PrintStream,PrintWriter类,两个类的方法一致,区别在于构造器 PrintStream:构造方法:接收File类型,接收字符串文件名,接收字节输出流(Outpu ...

  8. JDK中工具类的使用

    JDK中内置了很多常用的工具类,且多以“s”结尾,如:集合工具类Collections,数组工具类Arrays,对象工具类Objects,文件工具类Files,路径工具类Paths,数学工具类Math ...

  9. 基于JavaMail开发邮件发送器工具类

    基于JavaMail开发邮件发送器工具类 在开发当中肯定会碰到利用Java调用邮件服务器的服务发送邮件的情况,比如账号激活.找回密码等功能.本人之前也碰到多次这样需求,为此特意将功能封装成一个简单易用 ...

随机推荐

  1. 玩Web虎-运行时受保护文件不可复制

    1. 直接复制粘贴,提示“操作无法完成,因为文件已在system中打开” 2.拔下加密锁后,复制粘贴,依然上错 3.用NoVirusThanks的 kernel-mode driver loader ...

  2. 超链接<a>标签用法

    1.a标签点击事件 1>1a href="javascript:js_method();" 这是我们平台上常用的方法,但是这种方法在传递this等参数的时候很容易出问题,而且 ...

  3. Odoo发送短信

    转载请注明原文地址:https://www.cnblogs.com/cnodoo/p/9281581.html 一:阿里云短信服务注册 1:开通短信业务:实名认证的个人用户是免费开通:企业用户需要提供 ...

  4. mac下用xattr命令来删除文件的扩展属性

    mac下发现不能用记事本打开文本文件,ls -la 发现格式后面有个@ wenke-mini:changeServer wenke$ ls -la total 144 drwxr-xr-x  20 w ...

  5. java基础二 java的跨平台特性

    一:java跨平台的特性: 1.生成不平台无关系的字节码. 2.通过和平台有关的jvm即java虚拟机来执行字节码.jvm不跨平台. 图示: 疑问:1.为什么我们不直接写字节码? 因为字节码只有jvm ...

  6. MySQL(一)索引的创建和删除

    索引是存储引擎用于快速找到记录的一种数据结构,这是索引的基本功能. 索引对于良好的性能非常关键.尤其是当表中的数据量越来越大时,索引对性能的影响愈发重要.接下来将讲述如何创建.查看和删除索引. 索引分 ...

  7. traefik-Ingress边缘路由器落地到微服务

    1.理解Ingress 简单的说,ingress就是从kubernetes集群外访问集群的入口,将用户的URL请求转发到不同的service上.Ingress相当于nginx.apache等负载均衡方 ...

  8. openshift 持续集成与部署 -- 构建部署流水线

    Jenkins持续构建说得更直白点,就是各种项目的"自动化"编译.打包.分发部署.j跟svn.git能无缝集成,也支持直接与知名源代码托管网站,比如github.bitbucket ...

  9. 404 Note Found 队-Beta7

    目录 组员情况 组员1:胡绪佩 组员2:胡青元 组员3:庄卉 组员4:家灿 组员5:恺琳 组员6:翟丹丹 组员7:何家伟 组员8:政演 组员9:黄鸿杰 组员10:何宇恒 组员11:刘一好 展示组内最新 ...

  10. Hadoop应用开发,常见错误

    错误1:在windows执行mr Exception in thread "main" java.lang.UnsatisfiedLinkError: org.apache.had ...