gpt4 book ai didi

java - 如何将curl代码转换成java

转载 作者:太空宇宙 更新时间:2023-11-04 13:33:56 26 4
gpt4 key购买 nike

我是 android 和 java 新手,我想从这个 API 获取访问数据。

我们需要做的就是将其转换为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"

最佳答案

您给定的 API 具有 header 和基本 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
}

现在调用该函数并传递 url 以及您的 header API token ,

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)

关于java - 如何将curl代码转换成java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31890027/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com