这两天遇到一个问题 ,与一个渠道联调接口,http请求,展示ptf 的需求,服务方以一个二进制的方式返回。
当时我们在一开始开发的时候,我们按照读取文件的方式处理,本地存一个ptf 的方式 ,以流的方式读取,然后以流的方式写出
这样,是可以进行的
@RequestMapping(value = "/savePrepayOrder")
public void call(HttpServletRequest request, HttpServletResponse response) throws NoSuchAlgorithmException, IOException {
File file = new File("D://001.pdf");
InputStream in = null;
response.setContentType("application/pdf"); // 设置返回内容格式
OutputStream os = null;
byte[] b = new byte[1000];
try {
System.out.println("以字节为单位读取文件内容,一次读一个字节:");
// 一次读一个字节
in = new FileInputStream(file);
os = response.getOutputStream(); // 创建输出流
int n;
while ((n = in.read(b)) != -1) {
os.write(b);
}
os.flush();
os.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
但是当我们通过http的的方式,获取到他们的流,然后以同样的方式进行转换是不行的 ,前端无法获取ptf内容
package com.paic.dmz.app.biz.pay;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.paic.common.utils.HttpUtil;
import com.paic.common.utils.HttpUtil1;
import com.paic.dmz.app.biz.lifeService.customerService.outer.openapi.OpenAPIClient;
import com.paic.dmz.app.biz.lifeService.customerService.outer.openapi.OpenAPIConstant;
import com.paic.dmz.app.biz.lifeService.customerService.outer.openapi.OpenAPIRequest;
@Controller
@RequestMapping("outer")
public class OuterController {
private static Log log = LogFactory.getLog(JinGuanJiaPayController.class);
private String notifyUrl = "investment.action";
private final static int CONNECTION_TIME_OUT = 10000;
public static final int READDATA_TIMEOUT = 10000;// 数据读取等待超时
@Autowired
private OpenAPIClient openAPIClient;
@RequestMapping(value = "/savePrepayOrder")
public void call(HttpServletRequest request, HttpServletResponse response) throws NoSuchAlgorithmException, IOException {
File file = new File("D://001.pdf");
InputStream in = null;
response.setContentType("application/pdf"); // 设置返回内容格式
OutputStream os = null;
byte[] b = new byte[1000];
String token = "eyJhbGciOiJIUzI1NiJ9.eyJjbGllbnRJZCI6IklMSUZFX0NPUkUiLCJleHAiOjE1NjA2MDM4NzgsImV4cGlyYXRpb25UaW1lIjoxNTYwNjAzODc4OTAxLCJpbnZva2VJbnRlcmZhY2UiOiIxRjhCMDgwMDAwMDAwMDAwMDAwMDk1OTRGRjZBREIzMDEwQzdERjY3Q0NFODE5RUM5MDhDQzIzQUIyQTYyREVDQ0Y4Qjc0NzY0NENFNzc5QTc0MzJGMzlFN0VCMkIzNkM1REIzQTQyRTQ2NjA4OUNGRTk3QjNGNjVDODkyNjQ1NzQxMTAyMkE5NDQwRkE2M0IxQ0NEMUVENDFFQjY0MkNGNDAxOTZCNzY2Qjg4RUNCOUZCNjhGRThGN0IxRTMwNjlDRDlDODFFRUI4OTVENzVDRDg0M0FBNThCNEY3NkEyMDg0MzRDNDYyQTIxODE5QjU0MUM2RDZFQjBBQzg2NjAyQzU2QjEyREYzM0M2NzE5M0Q5RDVENjRBNjY5RDNENUJBMDYzODU5RDU3MkY3Q0E5RTBEQjUwQjU5QUFBODg2NDIwRUI0MUEyRkYwOTEzNkEzQUQ0QkExQ0RDQTc2RTM5REMwMDFGMUZDN0IwRjBGQTg5NkUyMkIwNURDOEVGRkFCNDEyQjcwNDc2NTJGRkRFQkYyM0QyMDc0Qzk5NzRCMTJCQUZGMDE3QTUwQTUxNUNCNjdBMkFENzk2ODA1NzA0MzlFMTY3OUY2RUUyRTVEQThEMjc2QzQ2MkQ2Qjc1MkU5OUY5MzA3RDhCRURCNkYyNDJBNDhEMzg1NjAxNTI2OUI0OTQyM0JBQTkxRjY4REM0OEFDRjlFRTc0NzIxRDBEMzBGNkM4QTU5RjVEMUQ4QUQyODA2RTEzMTFERkMzRkZGNTM5MUUyQjFDODA0QzgyMDFEN0U1Mjc5NzBFRkM3NzQ0Q0U0NDU5NUU0QjAzNTUzMkE1RkNCQUMxODVGQzlDRUIzNUMzOUVGMDFFN0U5NEU4NzZCOUZGNDM4QkYzNUMzOTFGMENGOTE2NEIwRUNFNTYzQjY4QjFDQjEwREQ1Q0QyRjM2NjEyOUE3MjY0RDUwRkM1OTk0QjI3NzMyMDAxNTdBQjgyM0Q0QzMxNUYxQkQ3RjkwMTc5OUEzNEU3NDFGRDA0OUU2RjA3MDFBN0NDQkQwOTE0RUY2RTE3NjNDRUM2MTc1MTZGRjE2QkM2RjQ0NjQzREM3QzZFQkU3OTI0RDc4QzhGQkVDNzA3RTAwRTdGMDE4QTI2RkUwNTJEMDUwMDAwIn0.Ntpx5jirO92y-RjjN4npxePIlJ20QPAho4HrL2nkrMc";
String requesturl = "http://lcloud-api-springboot-bx-stg3-web-padis.paic.com.cn/zuul/lcloud-apollo-oth/valitype-oauth/product/getFileByteByPost?token="+token+"" ;
String request1 = "{\"planCode\": \"521\",\"versionNo\": \"521-1\",\"attachmentType\": \"1\"}";
HttpResponse response1 = null;
CloseableHttpClient httpClient = null;
try {
// HttpResponse ss = HttpUtil1.sendHttpsPost(requesturl, request,
// "application/json;charset=utf-8", null);
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 默认信任所有证书
public boolean isTrusted(X509Certificate[] arg0, String arg1) {
return true;
}
}).build();
SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
httpClient = HttpClients.custom().setSSLSocketFactory(ssf).build();
HttpPost httpPost = new HttpPost(requesturl);
// Authenticator.setDefault(new
// MyAuthenticator("gaowei399","741asd#fg"));
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIME_OUT).setSocketTimeout(READDATA_TIMEOUT)
// .setProxy(new HttpHost("10.37.84.36", 8080))
.build();
httpPost.setConfig(requestConfig);
httpPost.setEntity(new StringEntity(request1, "UTF-8"));
if (StringUtils.isNotBlank("application/json;charset=utf-8")) {
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
}
HttpResponse resp = httpClient.execute(httpPost);
String result = EntityUtils.toString(resp.getEntity(), HTTP.UTF_8);
System.out.println(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = response1.getEntity().getContent();
String result = EntityUtils.toString(response1.getEntity(), HTTP.UTF_8);
System.out.println("request="+result);
os = response.getOutputStream(); // 创建输出流
int n;
while ((n = in.read(b)) != -1) {
os.write(b);
}
os.flush();
os.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public OpenAPIRequest getOpenAPIRequest(String url) {
OpenAPIRequest req = new OpenAPIRequest();
经过讨论,我们将返回的返回的http流转成二进制,在通过OutputStream写出,这样成功完成任务
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 默认信任所有证书
public boolean isTrusted(X509Certificate[] arg0, String arg1) {
return true;
}
}).build();
SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
httpClient = HttpClients.custom().setSSLSocketFactory(ssf).build();
HttpPost httpPost = new HttpPost(requesturl);
// Authenticator.setDefault(new
// MyAuthenticator("gaowei399","741asd#fg"));
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIME_OUT).setSocketTimeout(READDATA_TIMEOUT)
// .setProxy(new HttpHost("10.37.84.36", 8080))
.build();
httpPost.setConfig(requestConfig);
httpPost.setEntity(new StringEntity(request1, "UTF-8"));
if (StringUtils.isNotBlank("application/json;charset=utf-8")) {
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
}
HttpResponse resp = ss;
in = resp.getEntity().getContent();
os = response.getOutputStream(); // 创建输出流
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 4];
int n = 0;
while (-1 != (n = in.read(buffer))) {
output.write(buffer, 0, n);
}
byte[] bytes = output.toByteArray();
System.out.println(bytes);
os.write(bytes);
os.flush();
os.close();