http接口实现跨域传递json实体(httpclient和jsonp方式都有)

传:

后台传

/**
     * 不知道谁写的发送post请求,很好用
     * @param url
     * @param requestJson
     * @return
     * @throws Exception
     */
    public static String sendPostJson(String url, String requestJson) throws Exception {
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(url);
        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(60000)
                .setConnectionRequestTimeout(60000)
                .setConnectTimeout(60000)
                .build();
        httpPost.setConfig(requestConfig);

        CloseableHttpResponse response = null;

        try {
            //设置post请求方式为JSON
            httpPost.addHeader("Authorization", "Basic" + encryptBASE64("username", "password"));
            StringEntity data = new StringEntity(requestJson, "UTF-8");
            data.setContentType("application/json; charset=UTF-8");
            httpPost.setEntity(data);

            //发送post请求
            response = closeableHttpClient.execute(httpPost);
            if (response == null || response.getStatusLine() == null) {
                throw new Exception("发送POST请求失败,返回结果为空!");
            }

            //返回状态是否200
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                //得到请求结果
                HttpEntity entityRes = response.getEntity();
                if (entityRes != null) {
                    String responsetData = EntityUtils.toString(entityRes, "UTF-8");
                    return responsetData;
                }
            } else {
                throw new Exception("发送POST-JSON请求出错:" + response);
            }
        } catch (Exception e) {
            throw new Exception("发送POST请求出现异常,"+e.getMessage());
        } finally {
            try {
                // 关闭连接释放资源
                if (response != null) {
                    response.close();
                }
                if (closeableHttpClient != null) {
                    closeableHttpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return "";
    }

前台传:

 $.ajax({
            url: 'http://localhost:8080/demo/post',
            type: "post",
            contentType: "application/json",
            dataType: 'JSONP',
            async: false,
            data:
                {
                    word: 1234567
                }
        })

接收:controller接收,参数为HttpServletRequest(万能的)

@PostMapping("/post")
    public String post(HttpServletRequest request) {
        try {
            //对于jsonp
            //request.getParameterMap;
            //String word = request.getParameter("word");

				   //对于httpclient的post数据流
            InputStream inputStream = request.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String word = "";
            for (String str = ""; (str = bufferedReader.readLine()) != null;
                 word = word + str) {
                ;
            }
            bufferedReader.close();
            inputStream.close();

            JSONArray jsonArray = JSONArray.fromObject(word);
            List<Demo> demoList = JSONArray.toList(jsonArray,Demo.class);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值