在Java中调用第三方接口通常有以下几种方法:
1. 使用Java内置的`HttpURLConnection`类:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpClient {
public static void main(String[] args) {
try {
URL url = new URL("http://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int statusCode = connection.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. 使用Apache HttpClient库:
首先,在项目的`pom.xml`文件中添加Apache HttpClient的依赖:
org.apache.httpcomponents httpclient
4.5.13
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) {
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://example.com/api");
try {
HttpResponse response = httpClient.execute(httpGet);
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
3. 如果第三方接口提供了Java客户端库,可以直接使用该库调用接口,例如:
import com.example.ExternalInterface;
import com.example.ExternalInterfaceImpl;
public class ExternalInterfaceDemo {
public static void main(String[] args) {
ExternalInterface externalInterface = new ExternalInterfaceImpl();
externalInterface.method();
}
}
class ExternalInterfaceImpl implements ExternalInterface {
@Override
public void method() {
System.out.println("调用外部接口的方法");
}
}
请根据具体情况选择合适的方法,并注意处理可能出现的异常