将传进来的十六进制表示的字符串转换成byte数组 文件下载


/**
* 将传进来的十六进制表示的字符串转换成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();
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值