package com.shanhw.practice;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnHelper {
/**
* @param url
* @return 返回一个InputStream
*/
public static InputStream loadStreamFromURL(String url) {
BufferedInputStream bis = null;
HttpURLConnection httpConn = null;
URL urlObj;
try {
urlObj = new URL(url);
httpConn = (HttpURLConnection) urlObj.openConnection();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
bis = new BufferedInputStream(httpConn.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
if (httpConn != null) {
httpConn.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return bis;
}
/**
* @param url
* @return 返回一个byte[]
*/
public static byte[] loadByteFromURL(String url) {
byte[] byteObj = null;
HttpURLConnection httpConn = null;
URL urlObj;
try {
urlObj = new URL(url);
httpConn = (HttpURLConnection) urlObj.openConnection();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
IOHelper io = new IOHelper();
byteObj = io.streamToByte(httpConn.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (httpConn != null) {
httpConn.disconnect();
}
}
return byteObj;
}
/**
* @param url
* @param parameters
* @return
*/
public static String doPostSubmit(String url, String parameters) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
URL urlObj = null;
HttpURLConnection httpConn = null;
String returnData = null;
try {
urlObj = new URL(url);
httpConn = (HttpURLConnection) urlObj.openConnection();
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
if (parameters != null) {
bos = new BufferedOutputStream(httpConn.getOutputStream());
bos.write(parameters.getBytes());
bos.flush();
}
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
bis = new BufferedInputStream(httpConn.getInputStream());
IOHelper io = new IOHelper();
returnData = io.streamToString(bis);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
httpConn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return returnData;
}
}
HttpURLConnHelper
最新推荐文章于 2020-06-24 08:39:51 发布