Java http工具类post请求返回结果接收btye数组
时间: 2023-08-02 11:11:43 浏览: 198
http发送请求获取返回结果
和GET请求类似,POST请求也可以使用HttpURLConnection来发送。下面是一个示例代码,用于发送POST请求并接收返回结果的byte数组:
```java
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUtils {
public static byte[] doPost(String urlStr, String params) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setDoOutput(true);
byte[] data = params.getBytes("UTF-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.getOutputStream().write(data);
InputStream in = null;
byte[] result = null;
try {
in = conn.getInputStream();
int len;
byte[] buffer = new byte[1024];
ByteArrayOutputStream out = new ByteArrayOutputStream();
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
result = out.toByteArray();
} finally {
if (in != null) {
in.close();
}
conn.disconnect();
}
return result;
}
}
```
在这个示例中,我们首先设置了HTTP请求的方法为POST,并且设置了请求参数、请求头等信息。然后,我们通过调用conn.getOutputStream()方法获得输出流,将请求数据写入输出流中。最后,我们读取输入流并将其转换为byte数组,以便后续处理。请注意,我们使用ByteArrayOutputStream来动态扩展byte数组的大小,以便能够适应任意大小的返回结果。
阅读全文