如果不使用RestTemplate进行Rest调用,可以使用Java原生的HttpURLConnection类来发送HTTP请求。以下是一个使用HttpURLConnection发送GET请求的示例代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUtil {
public static String sendGetRequest(String url) throws IOException {
URL urlObj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
return response.toString();
} else {
throw new IOException("Get request failed with response code: " + responseCode);
}
}
public static void main(String[] args) {
try {
String url = "https://jsonplaceholder.typicode.com/posts";
String response = sendGetRequest(url);
System.out.println(response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
这是一个简单的GET请求示例,可以根据需要进行修改和扩展。使用HttpURLConnection发送POST请求也是类似的,只需要设置请求方法为"POST",并添加请求体数据即可。
需要注意的是,HttpURLConnection是Java原生的类,不像RestTemplate提供了很多高级功能,如自动序列化/反序列化JSON、处理异常等。因此,如果在项目中需要频繁进行Rest调用,建议使用RestTemplate或其他成熟的HTTP客户端库来简化开发和提高性能。