发送http的post请求并通过request接收post请求体

本文介绍了如何使用Java实现HTTP POST请求的发送及接收过程,包括设置SSL安全连接、超时时间和请求头等细节,并展示了如何从POST请求中读取请求体。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、http发送post请求:

/**
     * 发送post请求
     * @param url 请求url
     * @param content 请求参数
     * @return 请求结果。异常或者没拿到返回结果的情况下,请求结果为""
     */
	public static String doPostQuery(String url, String content, int time) throws IOException {
		if("yes".equals(flag)) {
        	SSLContext sc = null;
    		try {
    			sc = SSLContext.getInstance("SSL");
                sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
                        new java.security.SecureRandom());
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
URL console = new URL(null,url,new sun.net.www.protocol.https.Handler());
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.setDoOutput(true);
            conn.setConnectTimeout(time);
            conn.setReadTimeout(time);
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.connect();
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.write(content.getBytes("UTF-8"));
            // 刷新、关闭
            out.flush();
            out.close();
            InputStream is = null;
            ByteArrayOutputStream outStream = null;
try {
            	 is = conn.getInputStream();
                 if (is != null) {
                     outStream = new ByteArrayOutputStream();
                     byte[] buffer = new byte[1024];
                     int len = 0;
                     while ((len = is.read(buffer)) != -1) {
                         outStream.write(buffer, 0, len);
                     }
                     return new String(outStream.toByteArray());
                 }
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			if(outStream!=null)
    			outStream.close();
    			if(is!=null)
                is.close();

    		}
} else {
        	// 创建post请求
            PostMethod method = new PostMethod(url);
            setMethodHeader(method);

            try {
                RequestEntity requestEntity = new ByteArrayRequestEntity(content.getBytes("UTF-8"), "UTF-8");
                method.setRequestEntity(requestEntity);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
// 发出请求
            String result = "";
            int stateCode = 0;
            try {
                stateCode = createHttpClient(time).executeMethod(method);
            } catch (IOException e) {
                log.error("Http post request failure, reason could be: {}", e.getMessage());
                throw e;
            }
            log.info("Http post method, stateCode: {}, url: {}, body: {}", stateCode, url, content);

            // 请求成功
            if (stateCode == HttpStatus.SC_OK) {
                try {
                    result = method.getResponseBodyAsString();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
// 释放资源
            releaseHttpConnection(method);

            return result;
        }
		return null;
	}
2、request接收post体:

public static final byte[] readBytes(InputStream is, int contentLen) {
        if (contentLen > 0) {
            int readLen = 0;

            int readLengthThisTime = 0;

            byte[] message = new byte[contentLen];

            try {

                while (readLen != contentLen) {

                    readLengthThisTime = is.read(message, readLen, contentLen
                            - readLen);

                    if (readLengthThisTime == -1) {// Should not happen.
                        break;
                    }

                    readLen += readLengthThisTime;
                }

                return message;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return new byte[] {};
    }

 @RequestMapping(value = "/test")
    public void testHttp(HttpServletRequest request) {
        try{
            request.setCharacterEncoding("UTF-8");
            int size = request.getContentLength();
            System.out.println(size);

            InputStream is = request.getInputStream();

            byte[] reqBodyBytes = readBytes(is, size);

            String res = new String(reqBodyBytes);
            //获取了post请求中请求体的内容
            System.out.println("请求体:"+res);
        } catch (Exception e) {

        }
        System.out.println("获取了结果");

    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值