Skip to content
Advertisement

How to send this JSON POST request in Java using volley

POST request in Postman

{“data”:[“dog”,45,256,256,2,5]}

Advertisement

Answer

i think that you First need to create your post request like this: (you will need to change the headers and parameters depending on what you are currently using in your Postman

URL objUrl = new URL("https://hf.space/embed/multimodalart/talentdiffusion/+api/predict/");

HttpURLConnection con = (HttpURLConnection) objUrl.openConnection();

// Setting the request
con.setRequestMethod("POST");
con.setDoOutput(true);

//add request header (you can add as many as needed
con.setRequestProperty("API-Authorization", "[REPLACE WITH YOU API KEY]");
con.setRequestProperty("[REPLACE WITH HEADER NAME]", "[REPLACE WITH HEADER VALUE]");
// ....

// Setting the data that need to be sent in the body of the request
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
String data = "{"data", ["dog",45,256,256,2,5"]}";
wr.write(data);
wr.flush();
wr.close();

// Storing the response code in an integer value
int code = con.getResponseCode();

// And if you want to get the api's response you can do this
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
      response.append(inputLine);
     }
in.close();

//Then you do what you want with your response

The previous one is a normal way of sending HTTP requests. Using Volley requests will be something like :

// Create a requestQueue object
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://hf.space/embed/multimodalart/talentdiffusion/+api/predict/";
/*JSONObject data = new JSONObject("{"data", 
 ["dog",45,256,256,2,5"]}");*/
 // Replace the previous line with these :
 /* {"data":[ "dog",45,256,256,2,5]}*/

JSONObject data = new JSONObject();
JSONArray arr = new JSONArray();
arr.put("dog");
arr.put(45);
arr.put(256);
arr.put(256);
arr.put(2);
arr.put(5);

data.put("data", arr);

// Request a response from the api
Stringrequest stringRequest = new StringRequest( Request.Method.POST,
    url,
    data,
    new Response.Listener<String>(){
      @Override
      public void onResponse(String response) {
        // Perform your actions here
      }
    },
    new Response.ErrorListener() {
       @Override
       public void onErrorResponse(VolleyError error) {
          // Perform your events here
       }
    }
);

// Add the request to the queue
queue.add(stringRequest);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement