Android examples for Network:HTTP Response
get Response Body As Byte via URL
//package com.java2s; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class Main { public static byte[] getResponseBodyAsByte(String url) { byte[] value = null; value = getResponseBodyAsByte(null, null, url); return value; }// w w w. j av a 2 s. c om public static byte[] getResponseBodyAsByte(String cookie, String url) { byte[] value = null; value = getResponseBodyAsByte(null, cookie, url); return value; } public static byte[] getResponseBodyAsByte(String refence, String cookie, String url) { byte[] result = null; URL urlO = null; HttpURLConnection http = null; InputStream is = null; ByteArrayOutputStream out = null; try { urlO = new URL(url); http = (HttpURLConnection) urlO.openConnection(); if (null != refence) { http.addRequestProperty("Referer", refence); } if (null != cookie) { http.addRequestProperty("Cookie", cookie); } http.addRequestProperty("Cache-Control", "no-cache"); http.addRequestProperty("Connection", "keep-alive"); http.setConnectTimeout(5 * 1000); http.setReadTimeout(10 * 1000); http.connect(); int code = http.getResponseCode(); if (code == HttpURLConnection.HTTP_OK) { int length = http.getContentLength(); if (length > 0) { System.out.println("???????:" + length); out = new ByteArrayOutputStream(); is = http.getInputStream(); int ch; byte[] buffer = new byte[2048]; while ((ch = is.read(buffer)) != -1) { out.write(buffer, 0, ch); out.flush(); } result = out.toByteArray(); } } } catch (Exception e) { System.err.println(e); } finally { if (null != http) { http.disconnect(); } if (null != out) { try { out.close(); } catch (IOException e) { } } } return result; } }