java通過Http請求訪問網路圖片或檔案返回byte陣列的兩種方式
阿新 • • 發佈:2019-01-06
第一種方式,使用HttpURLConnection
使用HttpURlConnection傳送一個get請求,開啟一個連線,從連接獲取到流,將流轉成byte陣列
/**
* 發起Get請求
*
* @param urlStr
* @return
*/
public final static byte[] doGetRequestForFile(String urlStr) {
InputStream is = null;
ByteArrayOutputStream os = null;
byte[] buff = new byte[1024 ];
int len = 0;
try {
URL url = new URL(UriUtils.encodePath(urlStr, DEFAULT_CHARSET));
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Content-Type", "plain/text;charset=" + DEFAULT_CHARSET);
conn.setRequestProperty("charset", DEFAULT_CHARSET);
conn.setDoInput(true );
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setReadTimeout(DEFAULT_TIME_OUT);
conn.connect();
is = conn.getInputStream();
os = new ByteArrayOutputStream();
while ((len = is.read(buff)) != -1) {
os.write(buff, 0, len);
}
return os.toByteArray();
} catch (IOException e) {
log.error("發起請求出現異常:", e);
return null;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
log.error("【關閉流異常】");
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
log.error("【關閉流異常】");
}
}
}
return result;
}
引入的類:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
第二種,使用OkHttpClient傳送get請求
使用OkHttpClient直接模擬request請求和response
public final static byte[] sendGetForFile(String url) {
InputStream inputStream = null;
Request req = (new Request.Builder()).url(url).get().build();
Response response = null;
try {
response = new OkHttpClient().newCall(req).execute();
if (!response.isSuccessful()) {
log.error("【呼叫HTTP請求異常】 code:{},message:{}", response.code(), response.message());
return null;
}
inputStream = response.body().byteStream();
return inputToByte(inputStream);
} catch (IOException e) {
log.error("發起請求出現異常:", e);
return null;
} finally {
try {
inputStream.close();
} catch (IOException var12) {
log.error("【關閉流異常】");
}
}
return result;
}
inputToByte方法:
/**
* 流轉byte陣列
*
* @param inputStream
* @return
* @throws IOException
*/
private static byte[] inputToByte(InputStream inputStream) throws IOException {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int rc;
while ((rc = inputStream.read(buff, 0, 1024)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] in2b = swapStream.toByteArray();
return in2b;
}
OkHttpClient傳送post請求
public static byte sendPostForFile(String url, String json) {
InputStream inputStream = null;
try {
RequestBody requestBody = RequestBody.create(JSON, json);
Request request = (new Builder()).url(url).post(requestBody).build();
Response response = new OkHttpClient().newCall(request).execute() ;
if (!response.isSuccessful()) {
log.error("【呼叫HTTP請求異常】 code:{},message:{}", response.code(), response.message());
return null;
}
inputStream = response.body().byteStream();
return inputToByte(inputStream);
} catch (IOException var13) {
logger.error("【post請求異常】", var13);
return null;
} finally {
try {
inputStream.close();
} catch (IOException var12) {
log.error("【關閉流異常】");
}
}
return result;
}