天天看點

Post/Get 請求

寫需求的時候需要經常性的需要自己組裝發送post/get請求,經常上網查或者自己自己寫,可太麻煩了,還是自己寫一下友善以後用。

上幹貨了!

Get 請求

/**
     * 發送get請求
     *
     * @param url 連結位址
     * @param apikey需要傳遞的密鑰
     * @param secretKey需要傳遞的密鑰
     * 如果不需要這兩個字段的可以取消不傳
     * @return
     */
    public String doGet(String url, String apikey, String secretKey) {
        HttpClient httpClient = null;
        HttpGet httpGet = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpGet = new HttpGet(url);
            httpGet.setHeader("Accept", "application/json;charset=UTF-8;");
            httpGet.setHeader("Content-Type", "application/json;charset=UTF-8;");
            httpGet.setHeader("apikey", apikey);
            httpGet.setHeader("secretKey", secretKey);
            HttpResponse response = httpClient.execute(httpGet);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "utf-8");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

 public class SSLClient extends DefaultHttpClient {
        public SSLClient() throws Exception {
            super();
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain,
                                               String authType) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain,
                                               String authType) throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = this.getConnectionManager();
            SchemeRegistry sr = ccm.getSchemeRegistry();
            sr.register(new Scheme("https", 443, ssf));
        }
    }
           

Post 請求

/**
     * 發送 post請求
     */
    public String sendPost(String json, String URL) {
        String obj = null;
        // 建立預設的httpClient執行個體.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 建立httppost
        HttpPost httppost = new HttpPost(URL);
        httppost.addHeader("Content-type", "application/json; charset=utf-8");
        httppost.setHeader("Accept", "application/json");
        try {
            StringEntity s = new StringEntity(json, Charset.forName("UTF-8")); // 對參數進行編碼,防止中文亂碼
            s.setContentEncoding("UTF-8");
            httppost.setEntity(s);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                // 擷取相應實體
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    obj = EntityUtils.toString(entity, "UTF-8");
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉連接配接,釋放資源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return obj;
    }
           
/**
     * @param url
     * @param requestBody 請求參數
     * @param charsetName 位元組編碼格式
     * @param headers 請求頭
     * @return 
     * @throws IOException
     */
    public String post(String url, String requestBody, String charsetName, List<Header> headers) throws IOException {
        byte[] requestBytes = requestBody.getBytes(charsetName);
        headers.add(new BasicHeader(HttpHeaders.CONTENT_ENCODING, charsetName));
        ByteArrayEntity requestEntity = new ByteArrayEntity(requestBytes);
        CloseableHttpResponse httpResponse = postForHttpResponse(url, requestEntity, headers);
        log.info("response status code:{}", httpResponse.getStatusLine().getStatusCode());
        HttpEntity responseEntity = httpResponse.getEntity();
        String responseBody = EntityUtils.toString(responseEntity, UTF8);
        EntityUtils.consume(responseEntity);
        if (HttpUtils.ConnectionMode.ONCE_MODE.equals(mode)) {
            httpResponse.close();
        }
        log.debug("response entity:\n{}", responseBody);
        return responseBody;
    }