2015-08-08 148 views
1

我是android和java中的新手我想從此API訪問數據。如何將curl代碼轉換爲java

所有我們需要做這個轉換成Java代碼

curl --include --header "X-Access-Token: YOUR_API_TOKEN_HERE" "http://api.travelpayouts.com/v2/prices/latest?currency=rub&period_type=year&page=1&limit=30&show_to_affiliates=true&sorting=price&trip_class=0" 

回答

0

你給定的API有一個頭和基本GET格式。這可以輕鬆地在Java中轉換。

查看代碼示例,

public String httpGet(String s, String api_token) { 
    String url = s; 
    StringBuilder body = new StringBuilder(); 
    httpclient = new DefaultHttpClient(); // create new httpClient 
    HttpGet httpGet = new HttpGet(url); // create new httpGet object 
    httpGet.setHeader("X-Access-Token", api_token); 

    try { 
     response = httpclient.execute(httpGet); // execute httpGet 
     StatusLine statusLine = response.getStatusLine(); 
     int statusCode = statusLine.getStatusCode(); 
     if (statusCode == HttpStatus.SC_OK) { 
      // System.out.println(statusLine); 
      body.append(statusLine + "\n"); 
      HttpEntity e = response.getEntity(); 
      String entity = EntityUtils.toString(e); 
      body.append(entity); 
     } else { 
      body.append(statusLine + "\n"); 
      // System.out.println(statusLine); 
     } 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     httpGet.releaseConnection(); // stop connection 
    } 
    return body.toString(); // return the String 
} 

現在調用該函數並通過網址與你的頭API令牌一起,

httpGet("http://api.travelpayouts.com/v2/prices/latest?currency=rub&period_type=year&page=1&limit=30&show_to_affiliates=true&sorting=price&trip_class=0", YOUR_API_TOKEN) 
+0

感謝我檢查 –

+0

嘿響應函數不是在android系統 –

+0

發現我們在哪裏定義這個響應 –