需要从PHP翻译成Java

时间:2016-09-29 21:20:35

标签: java php apache httpclient apache-httpclient-4.x

尝试使用QwintryLogistics API,PHP中的所有文档示例,我根本不了解PHP,使用Java编码。在文档中,所需的请求如下所示:

<?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);
Java中的

编码方法:

@Override
public String getCost(double weight, String unitsW, String toPickUp, boolean insurance, double value) throws URISyntaxException, IOException, HttpException {
    String url = BASE_URL + "/api/cost/";
    CloseableHttpClient client = HttpClients.createDefault();
    URIBuilder builder = new URIBuilder(url);
    builder
            .addParameter("weight", String.valueOf(weight))
            .addParameter("delivery_pickup", toPickUp)
            .addParameter("insurance", String.valueOf(insurance))
            .addParameter("items_value", String.valueOf(value))
            .addParameter("retail_pricing", String.valueOf(RETAIL_PRICING));

    HttpUriRequest request = new HttpPost(builder.build());
    request.addHeader("User-Agent", USER_AGENT);
    request.addHeader("Authorization", "Bearer " + API_KEY);

    HttpResponse response = client.execute(request);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
    return result.toString();
}

但不断得到回应:

{"success":false,"errorCode":0,"errorMessage":"params are empty"}

我认为问题在于为请求设置参数。请帮助我用Java术语翻译请求参数的结构。

1 个答案:

答案 0 :(得分:1)

您的PHP代码数据参数不是路径参数,而是请求参数。您必须将它们写入请求正文,而不是将它们附加到URL中。

您可以在相关问题中查看如何执行此操作:Java - sending HTTP parameters via POST method easily

但是,我会查看更高级别的REST服务客户端,例如CXFJersey