在之前的项目中,使用传统的HttpClient来返回一个图片信息流的时候总是报错,最后发现是因为传统的传输方式会对流的大小有限制,当超过某个值的时候就会报异常,最后决定使用OkHttp框架来解决这个问题。实例如下:
package com.xiao.controller; import okhttp3.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.TimeUnit; public class AdController { private Logger logger= LoggerFactory.getLogger(this.getClass()); private 。okHttpClient= new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .retryOnConnectionFailure(true) .build(); private String appcenterUrl="http://localhost:8085"; @RequestMapping(value = "getImage",method = {RequestMethod.GET,RequestMethod.POST}) public void getImageUrl(HttpServletResponse response){ Map<String,String> params=new HashMap<>(); String url=appcenterUrl+"/adCenter"+"/downloadImg"; try { Response res = exPost(url,params).execute(); if(res.code()==200){ if(res.body()!=null){ byte[] bytes = res.body().bytes(); String contentType = res.header("Content-type"); if(contentType!=null){ response.addHeader("Content-type",contentType); } response.addHeader("Content-Length",String.valueOf(bytes.length)); try (ServletOutputStream outputStream=response.getOutputStream()){ outputStream.write(bytes); outputStream.flush(); }catch (IOException e){ response.setStatus(500); } } }else { logger.error("错误码"+res.code()); response.setStatus(500); } }catch (IOException e){ logger.error("错误信息"+e); response.setStatus(500); } } private Call exPost(String url, Map<String,String> addedParams) { FormBody.Builder params = new FormBody.Builder(); Iterator var5 = addedParams.entrySet().iterator(); while (var5.hasNext()){ Map.Entry<String, String> next = (Map.Entry) var5.next(); params.add(next.getKey(),next.getValue()); } Request request = (new okhttp3.Request.Builder()) .url(url) .post(params.build()) .build(); return okHttpClient.newCall(request); } private Call post(String url, Map<String, String> addedParams) { FormBody.Builder params = new FormBody.Builder(StandardCharsets.UTF_8); for (Map.Entry<String, String> entry : addedParams.entrySet()) { params.add(entry.getKey(), entry.getValue()); } Request request = new Request.Builder() .url(url) .post(params.build()) .build(); return okHttpClient.newCall(request); } }
这里的
OkHttpClient 中的时间你们可以自己选择定义的,不一定是30
这里还有一个需要大家思考的是如果用的是get请求,那这个又是怎么写?或者地址之后还有其他的参数,这个get可能需要自己去拼接,就像我们平时输入的一个地址一样