Java Http GET POST发送请求

Java Http GET POST发送请求

本文写了1个java 发送GET请求以及2个java 发送POST请求,新手,不喜勿喷!

背景:

这是一个使用魔宝支付的demo,首先需要移动端提交商城订单,请求平台签名接口进行签名并获取支付所需要的要素,对支付公司返回的信息验签后返回移动端这些要素,移动端启动支付公司SDK进行支付交易,后续还有接收交易结果通知消息。

说明

  • GET核心:CloseableHttpClient和CloseableHttpResponse,HttpGet
  • POST核心:HttpURLConnection和HttpPost

功能步骤说明

  1. 第一步:GET请求从服务器签名接口进行签名操作;
  2. 第二步:GET请求至魔宝支付进行获取支付所需要素;
  3. 第三步:POST验签魔宝返回的签名信息,防篡改

静态变量

第一步:签名

  • 在交易之前需要使用支付方提供的证书进行签名交易订单

/**
*   签名订单信息
*/
public static JSONObject testHttpGet(String data) throws UnsupportedEncodingException {
        CloseableHttpClient httpClient = HttpClients.custom().disableContentCompression().build();
        StringBuffer qUrl = new StringBuffer(signUrl);
        qUrl.append("?tranData=" + URLEncoder.encode(data, "UTF-8"));
        HttpGet httpget = new HttpGet(new String(qUrl));
        try {
            CloseableHttpResponse httpResponse = httpClient.execute(httpget);
            HttpEntity entity = httpResponse.getEntity();
            //返回内容
            String res = EntityUtils.toString(entity, "UTF-8");
            return JSONObject.parseObject(res);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

第二步:获取支付要素

  • 使用支付方规定的格式,签名后请求支付公司接口得到支付所需要的要素,支付公司返回要素以及签名信息
public static String getPayElements(JSONObject json) throws UnsupportedEncodingException {
        if (json.containsKey("message") && json.containsKey("signature")) {
            String message = json.getString("message");
            String signature = json.getString("signature");
            String param = "message=" + message + "&signature=" + signature;
            String paramEncode = URLEncoder.encode(param, "UTF-8");

            CloseableHttpClient httpClient = HttpClients.custom().disableContentCompression().build();
            StringBuffer qUrl = new StringBuffer(mobaoUrl);
            qUrl.append("?message=" + URLEncoder.encode(message, "UTF-8"));
            qUrl.append("&signature=" + URLEncoder.encode(signature, "UTF-8"));
            HttpGet httpget = new HttpGet(new String(qUrl));
            try {
                CloseableHttpResponse httpResponse = httpClient.execute(httpget);
                HttpEntity entity = httpResponse.getEntity();
                //返回内容
                String res = EntityUtils.toString(entity, "UTF-8");
                return res;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

第三步:验签

  • 获取支付要素时支付公司返回签名信息,需要进行验签,防止信息被篡改。
public static JSONObject verifySign(JSONObject jsonObject) {
        if (jsonObject.containsKey("message") && jsonObject.containsKey("signature")) {
            String message = jsonObject.getString("message");
            String signature = jsonObject.getString("signature");

            try {
                //创建连接
                URL url = new URL(verifyUrl);
                HttpURLConnection connection = (HttpURLConnection) url
                        .openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setRequestMethod("POST");
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(true);
//                connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
                connection.setRequestProperty("Content-Type", "application/json");

                connection.connect();
                //POST请求
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                JSONObject obj = new JSONObject();
                obj.put("message", message);
                obj.put("signature", signature);
                out.writeBytes(obj.toString());
                out.flush();
                out.close();

                //读取响应
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String lines;
                StringBuffer sb = new StringBuffer("");
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), "utf-8");
                    sb.append(lines);
                }
                reader.close();
                // 断开连接
                connection.disconnect();
                return JSONObject.parseObject(sb.toString());
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

附:另外一个POST请求方式

public static String post(String json, String url) throws Exception{

        StringEntity entity = new StringEntity(json, "utf-8");
        entity.setContentType("application/json");

        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);

        HttpResponse response = client.execute(httpPost);
        InputStream inputStream = response.getEntity().getContent();
        StringBuffer buffer = new StringBuffer();
        InputStreamReader inputReader = new InputStreamReader(inputStream);
        BufferedReader bufferReader = new BufferedReader(inputReader);
        String str;
        while ((str = bufferReader.readLine()) != null) {
            buffer.append(str);
        }
        bufferReader.close();
        String jsonOut = buffer.toString();
        return jsonOut;
    }

我的联系方式:
- Q Q:1250052380
- 邮箱:1250052380@qq.com

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

羽轩GM

您的鼓励是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值