在Java中调用外部接口通常有以下几种方法:
1. 使用Java内置的`HttpURLConnection`类:
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpClientUtil {
public static String doPost(String pathUrl, String data) {
try {
URL url = new URL(pathUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
out.write(data);
out.flush();
out.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
} else {
throw new RuntimeException("Failed : HTTP error code : " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
2. 使用Apache HttpClient库:
首先,在Maven项目的`pom.xml`中添加依赖:
org.apache.httpcomponents httpclient
4.5.13
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static String callExternalAPI(String url, String jsonPayload) {
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", "application/json");
httpPost.setEntity(new StringEntity(jsonPayload));
try {
HttpResponse response = httpClient.execute(httpPost);
return EntityUtils.toString(response.getEntity());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
3. 使用Spring的`RestTemplate`:
import org.springframework.web.client.RestTemplate;
public class RestTemplateExample {
public static String callExternalAPI(String url, String payload) {
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.postForObject(url, payload, String.class);
return result;
}
}
调用外部接口的基本步骤包括:
导入接口所在的包。
创建接口的实现类的对象。
通过接口实例调用接口的方法。
请根据你的具体需求选择合适的方法,并注意处理异常和响应数据