Home > Software engineering >  How to send this JSON POST request in Java using volley
How to send this JSON POST request in Java using volley

Time:07-08

POST request in Postman

{"data", ["dog",45,256,256,2,5"]}

CodePudding user response:

Check this documentation that explains how to use Volley in Android.

https://google.github.io/volley/simple.html

CodePudding user response:

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\"]}");

// 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 one rrorResponse(VolleyError error) {
          // Perform your events here
       }
    }
);

// Add the request to the queue
queue.add(stringRequest);
  • Related