Http BODY中存放二进格式参数数据 的POST请求

方法一,使用原始HttpURLConnection方法

    public static byte[] post(String url, byte[] requestBytes) {
        // TODO 设置连接池
        InputStream in = null;
        byte[] data = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = null;
            try {
                conn = realUrl.openConnection();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/octet-stream");
            // 设置超时时间为1秒
            conn.setConnectTimeout(1);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);

            // 发送请求参数
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            dos.write(requestBytes);

            // flush输出流的缓冲
            dos.flush();

            InputStream raw = conn.getInputStream();

            in = new BufferedInputStream(raw);
            int contentLength = conn.getContentLength();
            data = new byte[contentLength];
            int bytesRead = 0;
            int offset = 0;
            while (offset < contentLength) {
                bytesRead = in.read(data, offset, data.length - offset);
                if (bytesRead == -1) {
                    break;
                }
                offset += bytesRead;
            }
            in.close();
        }catch (Exception e) {
            logger.error("Something went wrong when Call url: {}", e);
        }finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return data;
    }

方法二,使用HttpClient 4

    /**
     * 二进制流数据进行POST通信
     * @param url
     * @param bytes
     * @param headerMap
     * @return
     */
    public static byte[] post(String url, byte[] bytes, Map headerMap) {

        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new ByteArrayEntity(bytes));
        HttpResponse httpResponse = null;
        byte[] resBytes = null;
        // 是否需要设置Header
        if (headerMap != null && !headerMap.isEmpty()) {
            Set keySet = headerMap.keySet();
            for (String key : keySet) {
                httpPost.addHeader(key, headerMap.get(key));
            }
        }

        try {
            httpResponse = client.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            int contentLength = (int)httpEntity.getContentLength();
            // 由于返回的结果可能一次性读不完,所以用buff保存每次读取的数据,而当某次读取到的长度返回值为-1时表示读取结束
            byte[] buff = new byte[contentLength];
            int total = 0;
            int len;
            while ((len = httpEntity.getContent().read(buff)) != -1) {
                    for(int i = 0; i < len; i++) {
                        resBytes[total+i] = buff[i];
                    }
                    total = total + len;
            }
            if(total != contentLength) {
                logger.error("Read http post response buffer error, [{}]", url);
            }

        } catch (Exception e) {
            logger.error("Something went wrong when call ADXUrl", e);
        }finally {
            if(httpPost != null) {
                httpPost.releaseConnection();
            }
        }

        return resBytes;
    }

 

你可能感兴趣的:(01,JAVA,计算机网络)