Java Http GET POST發送請求

來源:互聯網
上載者:User

標籤:post   http   

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驗簽魔寶返回的簽名資訊,防篡改
靜態變數
  • 訂單資訊:private static String tranData = “XML訂單資訊”;
  • 簽名介面:private static String signUrl = “http://10.3.30.17:8099/chpay/v1/pay/mobao/sign“;
  • 驗簽介面private static String verifyUrl = “http://10.3.30.17:8099/chpay/v1/pay/mobao/signature/verify“;
  • 魔寶介面:private static String mobaoUrl = “http://182.148.123.7:8132/service“;
第一步:簽名
  • 在交易之前需要使用支付方提供的認證進行簽名交易訂單
/***   簽名訂單資訊*/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
- 郵箱:[email protected]

Java Http GET POST發送請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.