我想用POST方法调用一个REST API,我想在API中使用Android Studio在同一调用中传递表单数据和参数。
有解决办法吗?
试试这个:
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());
您需要以下导入:
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;
和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>