从Spring Boot控制器到另一台服务器的HTTP请求可以通过以下步骤来执行:
以下是一个示例代码,使用Apache HttpClient发送GET请求:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/sendRequest")
public String sendRequest() {
String url = "http://另一台服务器的IP地址/目标路径";
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity);
return responseBody;
} catch (Exception e) {
e.printStackTrace();
return "发送请求失败";
}
}
}
这个示例代码中,我们使用了Apache HttpClient库来发送GET请求。你可以根据需要选择其他HTTP客户端库,例如OkHttp。
注意:在实际应用中,为了提高性能和安全性,可能需要对HTTP请求进行进一步的配置和优化,例如设置连接池、超时时间、请求重试机制、SSL证书验证等。
领取专属 10元无门槛券
手把手带您无忧上云