Azure Java Web App get JSONObject from curl request

58 Views Asked by At

I am building a Java web app (JDK 17, Jakarta EE, Tomcat 10) and am using org.json to make a curl request to the PetFinder API.

When I deploy a .war file to my Azure Web App I get the Exception message: JSONObject["access_token"] not found.

I assume I need to configure Azure to communicate with https://api.petfinder.com, but I am stuck.

Here is my code combined into a single servlet.

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.nio.charset.Charset;

@WebServlet(name="petFinderServlet", value="/pet-finder")
public class PetFinderServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String api_key = "my_api_key";
            String api_secret = "my_api_secret";
            JSONObject json = readJsonFromCurl(String.format("curl -d \"grant_type=client_credentials&client_id=%s&client_secret=%s\" https://api.petfinder.com/v2/oauth2/token", api_key, api_secret));
            String access_token = json.getString("access_token");
            JSONObject json2 = JSONReader.readJsonFromCurl(String.format("curl -H \"Authorization: Bearer %s\" GET https://api.petfinder.com/v2/animals?type=dog", access_token));
            // more code
        } catch (IOException e) {

        }
    }

    private static String readAll(Reader rd) throws IOException {
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = rd.read()) != -1) {
            sb.append((char) cp);
        }
        return sb.toString();
    }

    public static JSONObject readJsonFromCurl(String curl) throws IOException, JSONException {
        Process process = Runtime.getRuntime().exec(curl);
        InputStream is = process.getInputStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String jsonText = readAll(rd);
            JSONObject json = new JSONObject(jsonText);
            return json;
        } finally {
            is.close();
        }
    }
}

Here are the dependencies from my pom.xml file.

<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>5.0.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20231013</version>
</dependency>
0

There are 0 best solutions below