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. Mac Item2 设置别名 永久生效

    使用 Item2 终端, 设置 别名的时候, 按照 网上的说法, 是 去 修改 用户目录下的   .bashrc   或者  .bash_profile 这两个文件都可以, 把 alias 写在 这两 ...

  2. codeforces 424D Biathlon Track

    codeforces 424D Biathlon Track 题意 题解 代码 #include<bits/stdc++.h> using namespace std; #define f ...

  3. Outliner大纲式笔记软件介绍

    简介 什么是Outliner An outliner (or outline processor) is a specialized type of word processor used to vi ...

  4. [转]HBase高可用性的新阶段

    From:http://m.csdn.net/article_pt.html?arcid=2823943 Apache HBase是一个面向线上服务的数据库,其原生支持Hadoop的特性,使其成为那些 ...

  5. CSS控制边界、边框与外轮廓

    一.CSS控制边界 1.内边距 padding(内边距也叫内填充) padding-bottom 长度/百分比 元件下端边线的空隙 padding-left 长度/百分比 元件左端边线的空隙 padd ...

  6. BZOJ3514:GERALD07加强版(LCT,主席树)

    Description N个点M条边的无向图,询问保留图中编号在[l,r]的边的时候图中的联通块个数. Input 第一行四个整数N.M.K.type,代表点数.边数.询问数以及询问是否加密. 接下来 ...

  7. Codeforces 1130 E.Wrong Answer 构造

    题目要求构造一组数据使得题目给出代码的anwser和正确答案恰好相差k,我们记题目给出代码的输出为ans1,正确答案为ans2. 我们假设已经有总和为s的p个正数,使得此时的ans1=ans2=s*p ...

  8. js如何将时间戳转换为标准时间

    function formatDate(date,fmt){ let o = { 'M+' : date.getMonth() +1, //月份 'd+' : date.getDate(), //日 ...

  9. leetcode 39. Combination Sum 、40. Combination Sum II 、216. Combination Sum III

    39. Combination Sum 依旧与subsets问题相似,每次选择这个数是否参加到求和中 因为是可以重复的,所以每次递归还是在i上,如果不能重复,就可以变成i+1 class Soluti ...

  10. LeetCode429. N-ary Tree Level Order Traversal

    题目来源:429. N-ary Tree Level Order Traversal https://leetcode.com/problems/n-ary-tree-level-order-trav ...