简单的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());
// }

}

猜你喜欢

转载自www.cnblogs.com/wupangzio/p/10573296.html