封装一个只传接口地址、请求参数、请求类型的第三方调用代码
时间: 2023-11-13 15:02:27 浏览: 103
好的,以下是一个简单的Java封装第三方接口的类,只需要传入接口地址、请求参数和请求类型:
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
public class ThirdPartyAPI {
public static String callAPI(String endpoint, Map<String, String> params, String requestMethod) {
try {
StringBuilder urlBuilder = new StringBuilder(endpoint);
if (params != null && !params.isEmpty()) {
urlBuilder.append("?");
for (Map.Entry<String, String> entry : params.entrySet()) {
urlBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
urlBuilder.deleteCharAt(urlBuilder.length() - 1);
}
URL url = new URL(urlBuilder.toString());
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod(requestMethod);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
connection.disconnect();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
}
```
注意这里的 `params` 参数是一个 `Map<String, String>` 类型,以键值对的形式传入请求参数。然后,你可以通过调用 `ThirdPartyAPI.callAPI("endpoint", params, "GET")` 或 `ThirdPartyAPI.callAPI("endpoint", params, "POST")` 等方式来调用第三方接口。
阅读全文