2016-09-29 71 views
1

試圖與QwintryLogistics API一起工作,PHP中的所有文檔示例,我根本不知道PHP,在Java上編碼。在文檔需要請求如下所示:需要翻譯從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

您的PHP代碼數據參數不是路徑參數,而是請求參數。您必須將它們寫入請求正文,而不是將它們附加到URL中。

你可以看到如何做到這一點在相關的問題:Java - sending HTTP parameters via POST method easily

不過,我想看看更高級別REST服務客戶端,如CXFJersey

+0

謝謝,開始使用Unirest庫,看起來很清晰,但沒有成功...... – zzheads

+0

請求主體的結構對我來說還不清楚,因爲我根本不知道PHP。如何使用String作爲計數器來創建參數數組? (params [weight],params [items_value],...等) – zzheads

+0

終於做到了! API文檔中存在錯誤,某些參數名稱錯誤。現在一切正常! – zzheads