簡單的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());
// }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM