項目背景:項目的后台部署在內網服務器linux_A上,在內網服務器linux_B上部署了nginx_A,linux_A和linux_B網絡是打通了的,前台代碼部署在nginx_A中。
同時在外網服務器linux_C中部署了nginx_B,nginx_B做了代理設置,所有請求到這台服務器都轉向了nginx_A(其實內網服務器linux_B和外網服務器linux_C之間存在一個跳板機,nginx_B中的請求都指向這個跳板機,然后跳板機調到linux_B)
問題描述:現在后端有一個接口,接口返回格式如下:
{"logo":"http://ip:port/image/xxxxxxxxxxx"}
這個logo的數據為一個完整的地址,后端將這個地址直接傳給前端,前端在<img src="">標簽中直接放進src屬性中,就可以顯示出圖片,但是問題是這個完整地址同屬於內網,在內網環境能正常顯示,但是在外網環境不能訪問。
解決辦法:獲取這個完整地址,在后台直接去請求,然后將請求結果加密,在加密后的字符串頭拼上"data:image/png;base64,",再將這傳字符串傳給前台,拼在src屬性中打開,工具方法的代碼如下:
//請求和加密方法
public static String encodeBase64File(String path) throws Exception {
//創建httpclient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
//創建Http get請求
HttpGet httpGet = new HttpGet(path);
//接收返回值
CloseableHttpResponse response = null;
try {
//請求執行
response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode()==200){
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = content.read(buff, 0, 100)) > 0) {
byteArrayOutputStream.write(buff, 0, rc);
}
byte[] buffer = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
content.close();
String encode = new BASE64Encoder().encode(buffer);
encode = encode.replaceAll("[\\s*\t\n\r]", "");
return encode;
}
} catch (IOException e) {
// TODO 自動生成的 catch 塊
e.printStackTrace();
}finally{
if(response!=null){
try {
response.close();
} catch (IOException e) {}
}
try {
httpClient.close();
} catch (IOException e) {}
}
return null;
}
