HttpClientUtil 接口调用 后台图片流回显前端

HttpClientUtil:

public static InputStream doPostimg(String url, Map<String, Object> param) {
		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;
		try {
			client = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			RequestConfig config = RequestConfig.custom().setConnectTimeout(35000)
					.setConnectionRequestTimeout(35000)
					.setSocketTimeout(60000)
					.build();
			httpPost.setConfig(config);
			if(param != null && param.size() > 0) {
				List<NameValuePair> entitys = new ArrayList<NameValuePair>();
				Iterator<Entry<String, Object>> iterator = param.entrySet().iterator();
				while(iterator.hasNext()) {
					Entry<String, Object> entry = iterator.next();
					entitys.add(new BasicNameValuePair(entry.getKey(),entry.getValue().toString()));
				}
				httpPost.setEntity(new UrlEncodedFormEntity(entitys,"UTF-8"));
			}
			response = client.execute(httpPost);
			HttpEntity entity = response.getEntity();
			return entity.getContent();
		}catch(Exception e) {
			logger.error(e.getMessage(),e);
			return null;
		}
	}

Controller :根据id 图片接口

 /**
     * 根据id 图片接口
     * @return
     */
    @RequestMapping("/downloadImageId")
	public void downloadImageId(HttpServletRequest request,HttpServletResponse response) {
        OutputStream out = null;
        try {
            String id = request.getParameter("id");
                response.setContentType( "text/html; charset=UTF-8");
                response.setContentType( "image/jpeg");
                out=response.getOutputStream();
            String url = "http://124.128.226.219:6041/api/downloadImage?eventIndexCode="+id+"&apk=zqzfj0210542&aps=93aa4040df0349ffb915db6260852b10";
            InputStream in = HttpClientUtil.doPostimg(url, null);
            byte[] buf = new byte[1024 *1024*10];
            int len;
            while((len = in.read(buf))!= -1) {
                out.write(buf, 0,len);
                out.flush();
            }
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

html:

<img   src="/event/downloadImageId?id=`+eventIndexCode+`" alt="png" width="200">

工具类 HttpClientUtil :

package com.langran.zfjevent.util;

import java.io.Closeable;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;

/**
 * @Description HTTP handler
 */
public class HttpClientUtil {

	private static final Logger logger = Logger.getLogger(HttpClientUtil.class);
	
	/**
	 * @Description HTTP GET请求
	 * @param url 地址
	 * @param param 参数
	 */
	public static String doGet(String url, Map<String, Object> param) {
		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;
		try {
			client = HttpClients.createDefault();
			if(param != null) {
				url += "?";
				Iterator<Entry<String, Object>> iterator = param.entrySet().iterator();
				while(iterator.hasNext()) {
					url = url + iterator.next()+"&";
				}
				url = url.substring(0,url.length()-1);
			}
			HttpGet httpGet = new HttpGet(url);
			RequestConfig config = RequestConfig.custom().setConnectTimeout(36000)
					.setConnectionRequestTimeout(36000)
					.setSocketTimeout(60000)
					.build();
			httpGet.setConfig(config);
			response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();
			return EntityUtils.toString(entity);
		}catch(Exception e) {
			logger.error(e.getMessage(),e);
			return null;
		}finally {
			try {
				if(response != null) {
					response.close();
				}
				if(client != null) {
					client.close();
				}
			}catch(Exception e) {
				
			}
		}
	}
	
	/**
	 * @Description HTTP header GET请求
	 * @param url 地址
	 * @param param 参数
	 */
	public static String doGetHeader(String url, Map<String, String> headers, Map<String, Object> param) {
		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;
		try {
			client = HttpClients.createDefault();
			if(param != null) {
				url += "?";
				Iterator<Entry<String, Object>> iterator = param.entrySet().iterator();
				while(iterator.hasNext()) {
					url = url + iterator.next()+"&";
				}
				url = url.substring(0,url.length()-1);
			}
			HttpGet httpGet = new HttpGet(url);
			Iterator<Entry<String, String>> iterator = headers.entrySet().iterator();
			//设置header信息
			while(iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				httpGet.setHeader(entry.getKey(), entry.getValue());
			}
			RequestConfig config = RequestConfig.custom().setConnectTimeout(36000)
					.setConnectionRequestTimeout(36000)
					.setSocketTimeout(60000)
					.build();
			httpGet.setConfig(config);
			response = client.execute(httpGet);
			HttpEntity entity = response.getEntity();
			return EntityUtils.toString(entity);
		}catch(Exception e) {
			e.getMessage();
			logger.error(e.getMessage(),e);
			return null;
		}finally {
			try {
				if(response != null) {
					response.close();
				}
				if(client != null) {
					client.close();
				}
			}catch(Exception e) {
				
			}
		}
	}
	
	/**
	 * @Description HTTP POST请求
	 * @param url 地址
	 * @param param 参数
	 */
	public static String doPost(String url, Map<String, Object> param) {
		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;
		try {
			client = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			RequestConfig config = RequestConfig.custom().setConnectTimeout(35000)
					.setConnectionRequestTimeout(35000)
					.setSocketTimeout(60000)
					.build();
			httpPost.setConfig(config);
			if(param != null && param.size() > 0) {
				List<NameValuePair> entitys = new ArrayList<NameValuePair>();
				Iterator<Entry<String, Object>> iterator = param.entrySet().iterator();
				while(iterator.hasNext()) {
					Entry<String, Object> entry = iterator.next();
					entitys.add(new BasicNameValuePair(entry.getKey(),entry.getValue().toString()));
				}
				httpPost.setEntity(new UrlEncodedFormEntity(entitys,"UTF-8"));
			}
			response = client.execute(httpPost);
			HttpEntity entity = response.getEntity();
			return EntityUtils.toString(entity);
		}catch(Exception e) {
			logger.error(e.getMessage(),e);
			return null;
		}finally {
			try {
				if(response != null) {
					response.close();
				}
				if(client != null) {
					client.close();
				}
			}catch(Exception e) {
				
			}
		}
	}
	
	/**
	 * @Description HTTPS POST请求
	 * @param url 地址
	 * @param param 参数
	 */
	@SuppressWarnings("resource")
	public static String doSSLPost(String url, Map<String, Object> param) {
		HttpClient client = null;
		HttpResponse response = null;
		try {
			client = new SSLClient();
			HttpPost httpPost = new HttpPost(url);
			RequestConfig config = RequestConfig.custom().setConnectTimeout(35000)
					.setConnectionRequestTimeout(35000)
					.setSocketTimeout(60000)
					.build();
			httpPost.setConfig(config);
			if(param != null && param.size() > 0) {
				List<NameValuePair> entitys = new ArrayList<NameValuePair>();
				Iterator<Entry<String, Object>> iterator = param.entrySet().iterator();
				while(iterator.hasNext()) {
					Entry<String, Object> entry = iterator.next();
					entitys.add(new BasicNameValuePair(entry.getKey(),entry.getValue().toString()));
				}
				httpPost.setEntity(new UrlEncodedFormEntity(entitys,"UTF-8"));
			}
			response = client.execute(httpPost);
			HttpEntity entity = response.getEntity();
			return EntityUtils.toString(entity);
		}catch(Exception e) {
			logger.error(e.getMessage(),e);
			return null;
		}finally {
			try {
				if(response != null) {
					((Closeable) response).close();
				}
				if(client != null) {
					((Closeable) client).close();
				}
			}catch(Exception e) {
				
			}
		}
	}
	
	/**
	 * @Description POST JSON 格式的请求
	 * @param url 地址
	 * @param param 请求参数 
	 */
	public static String doPostJson(String url, JSONObject param) {
		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;
		try {
			client = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			RequestConfig config = RequestConfig.custom().setConnectTimeout(35000)
					.setConnectionRequestTimeout(35000)
					.setSocketTimeout(60000)
					.build();
			httpPost.setConfig(config);
			StringEntity s = new StringEntity(param.toString(),Charset.forName("UTF-8"));
            s.setContentEncoding("utf-8");
            s.setContentType("application/json");
            httpPost.setEntity(s);
            response = client.execute(httpPost);
			HttpEntity entity = response.getEntity();
			return EntityUtils.toString(entity);
		}catch(Exception e) {
			logger.error(e.getMessage(),e);
			return null;
		}finally {
			try {
				if(client != null) {
					client.close();
				}
				if(response != null) {
					response.close();
				}
			}catch(Exception e) {
				
			}
		}
	}
	
	/**
	 * @Description 请求XML格式
	 * @param url
	 * @param xml
	 */
	public static String doPostXml(String url, String xml) {
		CloseableHttpClient httpClient = null;
		CloseableHttpResponse response = null;
		try {
			httpClient = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			RequestConfig config = RequestConfig.custom().setConnectTimeout(36000) //连接服务器超时时间
					.setConnectionRequestTimeout(36000)                            //请求超时时间
					.setSocketTimeout(60000)                                       //读取数据超时时间
					.build();
			httpPost.setConfig(config);
			//有参数设置参数
			StringEntity stringEntity = new StringEntity(xml, "UTF-8"); 
		    httpPost.setEntity(stringEntity);
			response = httpClient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			return EntityUtils.toString(entity,"UTF-8");
		}catch(Exception e) {
			logger.error(e.getMessage(),e);
			return "error";
		}finally {
			try {
				if(httpClient != null) {
					httpClient.close();
				}
				if(response != null) {
					response.close();
				}
			}catch(Exception e) {
				
			}
		}
	}
	
	/**
	 * @Description 有header的JSON请求
	 * @param url
	 * @param header
	 * @param param
	 */
	public static String headerJson(String url, Map<String, String> header, JSONObject param){
		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;
		try {
			client = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			RequestConfig config = RequestConfig.custom().setConnectTimeout(35000)
					.setConnectionRequestTimeout(35000)
					.setSocketTimeout(60000)
					.build();
			httpPost.setConfig(config);
			Iterator<Entry<String, String>> iterator = header.entrySet().iterator();
			while(iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				httpPost.setHeader(entry.getKey(), entry.getValue());
			}
			StringEntity s = new StringEntity(param.toString(),Charset.forName("UTF-8"));
            s.setContentEncoding("utf-8");
            s.setContentType("application/json");
            httpPost.setEntity(s);
            response = client.execute(httpPost);
			HttpEntity entity = response.getEntity();
			return EntityUtils.toString(entity);
		}catch(Exception e) {
			logger.error(e.getMessage(),e);
			return null;
		}finally {
			try {
				if(client != null) {
					client.close();
				}
				if(response != null) {
					response.close();
				}
			}catch(Exception e) {
				
			}
		}
	}
	public static InputStream doPostimg(String url, Map<String, Object> param) {
		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;
		try {
			client = HttpClients.createDefault();
			HttpPost httpPost = new HttpPost(url);
			RequestConfig config = RequestConfig.custom().setConnectTimeout(35000)
					.setConnectionRequestTimeout(35000)
					.setSocketTimeout(60000)
					.build();
			httpPost.setConfig(config);
			if(param != null && param.size() > 0) {
				List<NameValuePair> entitys = new ArrayList<NameValuePair>();
				Iterator<Entry<String, Object>> iterator = param.entrySet().iterator();
				while(iterator.hasNext()) {
					Entry<String, Object> entry = iterator.next();
					entitys.add(new BasicNameValuePair(entry.getKey(),entry.getValue().toString()));
				}
				httpPost.setEntity(new UrlEncodedFormEntity(entitys,"UTF-8"));
			}
			response = client.execute(httpPost);
			HttpEntity entity = response.getEntity();
			return entity.getContent();
		}catch(Exception e) {
			logger.error(e.getMessage(),e);
			return null;
		}
	}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值