要使用HttpClient進行POST請求并提交表單參數,您需要按照以下步驟進行操作:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://example.com/api/endpoint");
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("param1", "value1"));
params.add(new BasicNameValuePair("param2", "value2"));
httpPost.setEntity(new UrlEncodedFormEntity(params));
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
String responseContent = EntityUtils.toString(entity);
System.out.println(responseContent);
}
response.close();
httpClient.close();
完整的示例代碼如下:
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
public class HttpClientExample {
public static void main(String[] args) {
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://example.com/api/endpoint");
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("param1", "value1"));
params.add(new BasicNameValuePair("param2", "value2"));
httpPost.setEntity(new UrlEncodedFormEntity(params));
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
String responseContent = EntityUtils.toString(entity);
System.out.println(responseContent);
}
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
請注意,上述示例中使用了Apache HttpClient 4.5版本的庫。您需要確保在您的項目中引入了相關的依賴包。