Skip to content Skip to sidebar Skip to footer

Run Curl From Java Android

I have this curl command curl -X GET 'https://api.spotify.com/v1/search?q=Carlos+Vives&type=artist' -H 'Accept: application/json' -H 'Authorization: Bearer '

Solution 1:

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();
    }
}

Solution 2:

You can execute the command line using the following method and also you can change it to JsonObject using Gson.

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.


Post a Comment for "Run Curl From Java Android"