无法配置Unirest请求正文

时间:2016-09-29 23:48:37

标签: java php api httprequest unirest

提供服务以连接QwintryLogistics API(http://logistics.qwintry.com),在Java + Unirest库上编码,但API的所有文档都在PHP中,因此请求体的结构对我来说不清楚。 有关POST请求的部分文档:

<?php
    define('SITE_URL', 'logistics.qwintry.com');
    define('API_KEY', 'YOUR_API_KEY'); //don't forget to set your key!
    $url =  'http://'. SITE_URL .'/api/cost';
    $data = array ( 
        'params' => array(
            'weight' => 5, // in lb
            'delivery_pickup' => 'msk_1', // full list of pickup points can be retrieved from /api/locations-list
            'insurance' => true,
            'items_value' => 500, // declaration items total cost in USD
            'retail_pricing' => true // retail / wholesale pricing?
        ),
     );
    $data_string = http_build_query($data);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. API_KEY));
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS,  $data_string);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $response = curl_exec($ch);
    curl_close($ch);
    var_dump($response);

所以我需要帮助来配置我的Unirest POST请求。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

就这样:

    Map<String, Object> params = new HashMap<>();
    params.put("params[weight_kg]", weight);
    params.put("params[dimensions_cm]", dimensions);
    params.put("params[delivery_pickup]", toPickup);
    params.put("params[insurance]", insurance);
    params.put("params[items_value]", value);
    params.put("params[retail_pricing]", RETAIL_PRICING);

    String url = BASE_URL+"/api/cost";
    HttpResponse<JsonNode> jsonResponse = Unirest.post(url).fields(params).asJson();

完美的作品:)