字节转换、请求工具(一)

2014-11-24 02:03:51 · 作者: · 浏览: 3

工具类:

import java.io.BufferedReader;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

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 java.net.URLConnection;

public class TestTool {

/**

* 读取指定文件转成字节数组

*

* Aug 11, 2011

* @param 文件的路径

* @param 文件的名称

* @return 文件内容转成的字节数组

* @throws Exception

*/

public static byte[] read(String path, String fileName) throws Exception {

byte[] aaa = getContent(path, fileName);

return aaa;

}

/**

* 发送请求

*

* Aug 11, 2011

* @param 发送的字节数组

* @throws 连接异常

*/

public static void sendHttpRequest(byte[] strRequest) throws Exception {

URL url = null;

HttpURLConnection httpURLConnection = null;

OutputStream out = null;

// 要请求的URL

String strUrl = "http://10.10.92.105:8080/xxx/xxServlet";

try {

url = new URL(strUrl);

URLConnection urlcn = url.openConnection();

if (urlcn instanceof HttpURLConnection) {

httpURLConnection = (HttpURLConnection) urlcn;

httpURLConnection.setRequestMethod("POST");

httpURLConnection.setDoOutput(true);

httpURLConnection.setDoInput(true);

httpURLConnection.setConnectTimeout(900000);

httpURLConnection.setReadTimeout(900000);

httpURLConnection.setRequestProperty("Content-type",

"application/x-java-serialized-object");

out = httpURLConnection.getOutputStream();

out.write(strRequest);

// 返回状态正常

if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

System.out.println("----------------------------------------------------");

BufferedReader reader = new BufferedReader(

new InputStreamReader(httpURLConnection

.getInputStream()));

String line;

StringBuffer str = new StringBuffer();

while ((line = reader.readLine()) != null) {

str.append(line);

}

// 打印应答内容

System.out.println(str.toString());

}

}

} catch (Exception e) {

throw new Exception("内部服务器错误");

} finally {

// 关闭连接

if (httpURLConnection != null) {

httpURLConnection.disconnect();

}

// 关闭流

if (out != null) {

try {

out.flush();

out.close();

} catch (IOException e) {

throw new Exception("内部服务器错误");

}

}

}

}

/**

* 往文件里写byte数组

*

* Aug 11, 2011