Java 调用第三方接口(get/post)
在Java中调用第三方API接口通常使用HttpClient库。以下是使用HttpClient进行GET和POST请求的示例代码:
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) {
// 创建HttpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
// GET请求
HttpGet httpGet = new HttpGet("http://api.example.com/data");
HttpResponse getResponse = httpClient.execute(httpGet);
System.out.println("GET Response Status:: " + getResponse.getStatusLine().getStatusCode());
String getResponseBody = EntityUtils.toString(getResponse.getEntity());
System.out.println(getResponseBody);
// POST请求
HttpPost httpPost = new HttpPost("http://api.example.com/data");
String json = "{\"key\":\"value\"}";
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Content-type", "application/json");
HttpResponse postResponse = httpClient.execute(httpPost);
System.out.println("POST Response Status:: " + postResponse.getStatusLine().getStatusCode());
String postResponseBody = EntityUtils.toString(postResponse.getEntity());
System.out.println(postResponseBody);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
确保在项目中包含了Apache HttpClient依赖:
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
以上代码展示了如何使用HttpClient执行GET和POST请求。在实际应用中,你可能需要处理响应、添加请求头、处理异常等。
评论已关闭