'How to Call REST API with Body (form-data) and Params using POST method at same API? in Android Studio

I want to call an REST API with POST Method in which i want to pass body with form-data and Params at same call in API using Android Studio.

Is there any solution?



Solution 1:[1]

Try this:

String body = """
        data={
            "username": "admin",
            "first_name": "System",
            "last_name": "Administrator"
        }
        """;
StringEntity entity = new StringEntity(body,
    ContentType.APPLICATION_FORM_URLENCODED);

HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost("http://localhost:8080/register");
request.setEntity(entity);

HttpResponse response = httpClient.execute(request);
System.out.println(response.getStatusLine().getStatusCode());

You need following imports:

package org.kodejava.apache.http;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;

and depency:

<!--https://search.maven.org/remotecontent?filepath=org/apache/httpcomponents/httpclient/4.5.13/httpclient-4.5.13.jar-->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Munakas123