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

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("获取了结果");

    }



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
<?php class Request{ public static function post($url, $post_data = '', $timeout = 5){//curl $ch = curl_init(); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_POST, 1); if($post_data != ''){ curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); } curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_HEADER, false); $file_contents = curl_exec($ch); curl_close($ch);Post()函数用于向窗口发送非PowerBuilder预定义事件的消息,这个窗口可以是PowerBuilder应用的窗口,也可以是其它应用的窗口。Post()函数把发送的消息放置在指定窗口消息队列的尾部,然后返回到应用程序中,它并不等待相应事件事件处理程序的执行。这一点与Send()函数不同,Send()函数直接触发指定窗口相应的事件,执行事件处理程序后返回到调用应用中。因此,我们说Post()函数采用的是异步方式,Send()函数采用的是同步方式。Post()函数的参数handle指定接收消息的窗口句柄,对PowerBuilder窗口来说,使用Handle()函数可以得到该句柄。对其它应用程序的窗口来说,可以调用系统API函数查找窗口并得到相应窗口的句柄。如果应用程序要邮寄PowerBuilder定义事件(包括预定义事件和用户定义事件),那么使用PostEvent()函数既简单有方便。当应用程序在long参数位置指定一个字符串时,Post()函数复制一个该字符串的副本,然后将副本的地址传送给指定窗口。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值