http urll 接口的寫法

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * TODO 代碼僅做爲示例,未作優化和代碼複用等處理;<br />
 * TODO 使用時需根據實際狀況進行優化和改造
 */
public class HttpClientDemo {

    private static Logger logger = LoggerFactory.getLogger(HttpClientDemo.class);

    /**
     * app的應用id,開發和上線前聯繫前海一方獲取,須要保密存儲
     */
    private final static String APP_KEY = "db3a7jajk-dasd-a34d-ffs1-d32123fsfe43s";

    /**
     * app的密鑰,開發和上線前聯繫前海一方獲取,須要保密存儲
     */
    private final static String APP_SECRET = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxw6V3m50E2xGN7OZSG/t9qOpfi/VBUFJaIgEFc+sZhadiR7kqcWb3niadyS5okny/SLmN4oM676B4SlaW1BI4TVZ2oh4bP2c63dw0MzA+nTrBrfXVLGE83+66uv8z6d33XCMfxKmE/XnVdwrsj/3veVjNOGuCG2dMzTEIYAjGBQIDAQAB";

    public static void main(String[] args) {
// TODO 使用的post請求,若是是GET請求,需使用HttpGet,PUT使用HttpPut,DELETE使用HttpDelete
        HttpPost post = null;
        try {
            String token = getToken(); // 獲取token
            HttpClient httpClient = HttpClients.createDefault();
            post = new HttpPost("http://192.168.138.193:6060/api/kingdee/payment/info");
            // 構造消息頭
            post.setHeader("Content-type", "application/json; charset=utf-8");
            post.setHeader("Connection", "Close");
            // 每一個業務接口調用時,都必須提供token,前海一方將根據token檢測請求是否來自合法的三方
            // token有過時時間,在過時時間以後token須要從新獲取
            post.setHeader("token", token);

            String requestParameter = "{\"baoliNo\":\"BL-1903-000005\",\"billDate\":\"2019-03-11 14:29:57\",\"applyAmount\":1,\"payee\":\"江蘇優創公關策劃有限公司\",\"payProviderGUID\":\"447c9c78-884a-e811-80bd-90e2babd62d1\",\"applyDesc\":\"支付優創案名發佈會費用\",\"contractCode\":\"住宅開發常州公司-常州天寧區劉塘浜地塊(聯合操盤)-一期-2018-07-000852\",\"contractName\":\"蘇南公司--璞樾門第項目--案名發佈會\",\"applyCode\":\"dccz-2018-10-7427\",\"companyName\":\"常州億泰房地產開發有限公司\",\"payeeBank\":\"中國銀行股份有限公司常州新城支行\",\"payeeAccount\":\"496263424668\"}"; // 請求參數,按照不一樣的接口參數構造json字符串
            // 對請求參數進行加密
            String rsaParameter = rsaEncryptedString(requestParameter);

            // 構建消息實體
            StringEntity entity = new StringEntity(rsaParameter, Charset.forName("gbk"));
            entity.setContentEncoding("gbk");
            // 發送Json格式的數據請求
            entity.setContentType("application/json");
            
            
            //https://data.riskstorm.com/v1/news/57e0fdbcd266387351d0e5a4?apikey=BvAXwAfqr0b3QMg2OCuSrA  這樣類型的url
            post.setEntity(entity);

            HttpResponse response = httpClient.execute(post);

// 檢驗返回碼
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("請求出錯: " + statusCode);
            } else {
// TODO 這裏參考getToken方法中解析響應數據
            }
        } catch (Exception e) {
// TODO 按需處理異常
            e.printStackTrace();
        } finally {
            if (post != null) {
                try {
                    post.releaseConnection();
                    Thread.sleep(500);
                } catch (InterruptedException e) {
// TODO 按需處理異常
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 獲取訪問憑證的示例方法<br />
     * 建議實際使用時,作好token的緩存和檢測(當發現token超時後自動從新獲取);token在過時前可緩存使用
     *
     * @return token
     */
    static String getToken() {
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost post = null;
        try {
            post = new HttpPost("http://192.168.138.193:6060/api/auth/access/token");

            // 設置http請求頭的信息,目前僅限定了請求協議爲json,編碼爲utf-8
            // 構造消息頭
            post.setHeader("Content-type", "application/json; charset=utf-8");
            post.setHeader("Connection", "Close");
            // 構造請求的json參數,能夠經過fastjson、gson等框架來構造該字符串

            String requestParameter = "{\"appKey\":\"" + APP_KEY + "\",\"appSecret\":\"" + APP_SECRET + "\"}";

            // 構建消息實體
            StringEntity entity = new StringEntity(requestParameter, Charset.forName("gbk"));
            entity.setContentEncoding("gbk");
            // 發送Json格式的數據請求
            entity.setContentType("application/json");
            post.setEntity(entity);

            HttpResponse response = null;
            response = httpClient.execute(post);
            // 檢驗返回碼
            int statusCode = response.getStatusLine().getStatusCode();
            if (HttpStatus.SC_OK != statusCode) {
                throw new RuntimeException("獲取token的HTTP請求響應失敗,響應代碼:" + statusCode);
            }
            HttpEntity resultEntity = response.getEntity();
            if (resultEntity != null) {
                // TODO 如下爲解析響應的json結構,可按需優化爲定義一個POJO對象,並直接從json轉換爲json對象
                String resultString = EntityUtils.toString(resultEntity, "gbk");
                JSONObject resultJsonObject = JSON.parseObject(resultString);
                if (!resultJsonObject.containsKey("data")) {
                    throw new RuntimeException("響應數據結構有誤,響應數據爲:" + resultString);
                }
                JSONObject dataJsonObject = resultJsonObject.getJSONObject("data");
                if (!dataJsonObject.containsKey("token")) {
                    throw new RuntimeException("響應數據結構有誤(未包含token),響應數據爲:" + resultString);
                }
                // long expireTime = dataJsonObject.getLongValue("expireTime"); // 過時時間,表明多少毫秒後token將過時
                return dataJsonObject.getString("token");
            }
        } catch (IOException e) {
            // TODO 按需處理異常
            // e.printStackTrace();
            logger.error("獲取token出錯,這裏須要按照業務須要實現本身的錯誤處理邏輯", e);
        }
        return null;
    }

    /**
     * 加密請求參數
     *
     * @param jsonData 要加密的json參數
     * @return 加密後的參數字符串
     */
    static String rsaEncryptedString(String jsonData) {

        try {

            return RsaUtils.encryptedString(jsonData, APP_SECRET);
        } catch (Exception e) {
            // TODO 按需處理異常
            e.printStackTrace();
        }
        return null;
    }


}
相關文章
相關標籤/搜索