外部只能访问A的接口,不能通过A访问B
使用HttpPost进行请求,并获取InputStream流读取响应,再通过ResponseBodyEmitter进行流式响应。
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;
@RestController
@RequestMapping("sys/proxy")
public class KnowledgeBaseController {
@RequestMapping("/stream")
public ResponseBodyEmitter knowledgeBaseChat(@RequestBody paramJsonStringify) {
// 这里的URL就是请求地址
HttpPost httpPost = new HttpPost(URL);
httpPost.addHeader("Content-Type", "application/json");
httpPost.setEntity(new StringEntity(paramJsonStringify, StandardCharsets.UTF_8));
byte[] bytes = new byte[4096];
ResponseBodyEmitter emitter = new ResponseBodyEmitter();
Executors.newSingleThreadExecutor().execute(() -> {
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse execute = httpClient.execute(httpPost);
InputStream inputStream = execute.getEntity().getContent();
int len = 0;
while ((len = inputStream.read(bytes)) != -1) {
// 只保留bytes中有效数据
byte[] needSend = new byte[len];
System.arraycopy(bytes, 0, needSend, 0, len);
emitter.send(needSend);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
emitter.complete();
}
});
return emitter;
}
}