/**
* 将传进来的十六进制表示的字符串转换成byte数组
*
* @param hexString
* @return 二进制表示的byte[]数组
*/
private static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase(Locale.getDefault());
int length = hexString.length() / 2;
// 将十六进制字符串转换成字符数组
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
// 一次去两个字符
int pos = i * 2;
// 两个字符一个对应byte的高四位一个对应第四位
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
/**
* 将传进来的字符代表的数字转换成二进制数
*
* @param c
* 要转换的字符
* @return 以byte的数据类型返回字符代表的数字的二进制表示形式
*/
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
PostMethod get = new PostMethod(
"http://localhost:8080/servlet/getDoc");
String filePath = "d:/photo1.doc";
NameValuePair[] data = new NameValuePair[2];
NameValuePair nameValuePair1 = new NameValuePair("token", "4565465fgfdg");
NameValuePair nameValuePair2 = new NameValuePair("docId", "1101");
data[0] = nameValuePair1;
data[1] = nameValuePair2;
get.setRequestBody(data);
String result = "";
HttpClient client = new HttpClient();
try {
client.executeMethod(get);
byte[] responseBody = get.getResponseBody();
StringBuffer sb = new StringBuffer();
sb.append(get.getResponseBody());
result = new String(get.getResponseBody(), "utf-8");
String[] tt = result.split("\"");
File file = new File(filePath); // 用File类表示出源文件夹
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fo = new FileOutputStream(file);
// Blob bl = new BlobImpl(hexStringToBytes(tt[7]));
ByteArrayInputStream bi= new ByteArrayInputStream(hexStringToBytes(tt[7]));
InputStream in = bi;
int i;
byte[] buffer = new byte[20480];
while ((i = in.read(buffer)) != -1) {
fo.write(buffer, 0, i);
}
fo.close();
System.out.println("restConn-----------------------------------"+ tt[7]);
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}