简体   繁体   English

从Java Android运行curl

[英]Run curl from Java android

I have this curl command 我有这个curl命令

curl -X GET "https://api.spotify.com/v1/search?q=Carlos+Vives&type=artist" -H "Accept: application/json" -H "Authorization: Bearer <My API Key>"

How can I run it ,and get the JSON response from Android (Java)? 如何运行它,并从Android(Java)获取JSON响应?

You can execute the command line using the following method and also you can change it to JsonObject using Gson . 您可以使用以下方法执行命令行,也可以使用Gson将其更改为JsonObject

public static String executeCommand(String command) {
    StringBuilder output = new StringBuilder();
    try {
      Process proc = Runtime.getRuntime().exec(new String[] { "sh", "-c", command });
      BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));

      String line;
      while ((line = reader.readLine())!= null) {
        output.append(line + "\n");
      }
      proc.waitFor();
    } catch (Exception e) {
      e.printStackTrace();
    }

    return output.toString();
  }

[EDIT] [编辑]

Please this answer is never mind. 请这个答案没关系。

As his(cricket_007) comment, you need to use network library for Android or Java such as OkHttp or Retrofit . 在his(cricket_007)注释中,您需要使用适用于Android或Java的网络库,例如OkHttpRetrofit

I've found the solution , Thanks 我找到了解决方案,谢谢

 /**
 * Gets the response from http Url request
 * @param url
 * @return
 * @throws IOException
 */
public static String getResponseFromHttpUrl(URL url) throws IOException {

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.addRequestProperty("Accept","application/json");
    connection.addRequestProperty("Content-Type","application/json");
    connection.addRequestProperty("Authorization","Bearer <spotify api key>");

    try {
        InputStream in = connection.getInputStream();

        Scanner scanner = new Scanner(in);
        scanner.useDelimiter("\\A");

        boolean hasInput = scanner.hasNext();
        if (hasInput) {
            return scanner.next();
        } else {
            return null;
        }
    } finally {
        connection.disconnect();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM