import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUtil {
public static final int cacheLength = 2048;
/**
* 发送http请求
*
*/
public static byte[] request(String url, byte[] request) throws IOException {
HttpURLConnection urlConnection = null;
OutputStream out = null;
// OutputStreamWriter out = null;
InputStream in = null;
ByteArrayOutputStream bais = null;
byte[] response = null;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(1000000);
if (request != null) {
// out = new OutputStreamWriter(urlConnection.getOutputStream(), HTTP.UTF_8);//
out = urlConnection.getOutputStream();
out.write(request);
// out.write("isPage=false");
out.flush();
out.close();
}
in = urlConnection.getInputStream();
bais = new ByteArrayOutputStream();
byte[] bytes = new byte[cacheLength];
int byteIn = in.read(bytes);
while (byteIn != -1) {
bais.write(bytes, 0, byteIn);
byteIn = in.read(bytes);
}
response = bais.toByteArray();
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bais != null) {
try {
bais.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return response;
}
}
|