如何将curl代码转换为java [英] How to convert curl code into java

查看:1065
本文介绍了如何将curl代码转换为java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new in android and java I want to get access data from this API.

我们需要做的就是把它转换成java代码

All we need to do convert this into java code

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具有标头和基本GET格式。这可以很容易地用Java转换。

Your given API has a header and basic GET format. This can be converted in Java easily.

参见代码示例,

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与你的一起传递标头API令牌,

Now call the function and pass the url along with your 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)

这篇关于如何将curl代码转换为java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆