前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >httpPost发送字节流方法

httpPost发送字节流方法

作者头像
用户7043603
发布2022-02-24 18:20:55
1.6K0
发布2022-02-24 18:20:55
举报
文章被收录于专栏:用户7043603的专栏

发送字节流的post方法,代码:

public byte[] post(String url,byte[] bytes) throws Exception {

HttpPost httpPost = new HttpPost(url);

httpPost.setEntity(new ByteArrayEntity(bytes));

httpPost.setHeader("Content-type", "application/octet-stream;charset=UTF-8");

//这里是设置虚拟IP

String remoteIp = (int) (Math.random() * 255 + 1)+"."+(int) (Math.random() * 255 + 1)+"."+(int) (Math.random() * 255 + 1)+"."+(int) (Math.random() * 255 + 1);

httpPost.setHeader("X-Forwarded-For",remoteIp);

CloseableHttpResponse httpResponse = HttpClients.createDefault().execute(httpPost);

try {

HttpEntity entityResponse = httpResponse.getEntity();

int responseCode = httpResponse.getStatusLine().getStatusCode();

int contentLength = (int) entityResponse.getContentLength();

// OutputStream out = new ByteArrayOutputStream(contentLength);

if (contentLength <= 0)

throw new IOException("No response");

int total = 0;

int len ;

//respBuffer是一个缓存数组,缓存InputStream.read()的数据,由于可能一次取不全,所以分多次取,最后是-1时候不取了结束了

byte[] respBuffer = new byte[contentLength];

byte[] respBuffer1 = new byte[contentLength];

while ((len = entityResponse.getContent().read(respBuffer)) != -1 ){

for (int i=0;i<len;i++){

respBuffer1[total+i] = respBuffer[i];

}

total = total + len;

}

// System.out.println(entityResponse.getContent().read(respBuffer,0,contentLength));

if (total != respBuffer.length)

throw new IOException("Read response buffer error");

return respBuffer1;

} finally {

httpResponse.close();

}

}

————————————————

版权声明:本文为CSDN博主「天天学一点-然后不会用」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/xpf094/article/details/85627829

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档