HttpClient

package com.test.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.Base64Utils;

import com.alibaba.fastjson.JSONObject;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/***
 * http工具类
 *
 */
public class HttpClientUtil {

    /**
     * 发送get请求
     * 
     * @param url
     * @return
     */
    public static String get(String url) {
        String content = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            // 创建httpget.
            HttpGet httpget = new HttpGet(url);
            System.out.println("executing request " + httpget.getURI());
            // 执行get请求.
            CloseableHttpResponse response = httpclient.execute(httpget);
            response.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                System.out.println("--------------------------------------");
                // 打印响应状态
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    // 打印响应内容长度
                    content = EntityUtils.toString(entity);
                    System.out.println("Response content length: " + entity.getContentLength());
                    // 打印响应内容
                    System.out.println("Response content: " + content);
                }
                System.out.println("------------------------------------");
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content;
    }

    /**
     * 发送post请求
     * 
     * @param url
     * @param mapParams
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String post(String url, Map<String, String> mapParams) throws ClientProtocolException, IOException {
        String content = "";
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 创建httpPost
        HttpPost httpPost = new HttpPost(url);

        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000 * 60).setConnectTimeout(1000 * 60)
                .build();// 设置请求和传输超时时间
        httpPost.setConfig(requestConfig);

        CloseableHttpResponse response = null;

        // 创建参数队列
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        if (mapParams != null) {
            Set<Entry<String, String>> entrySet = mapParams.entrySet();
            for (Entry<String, String> entry : entrySet) {
                formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
        httpPost.setEntity(uefEntity);
        System.out.println("executing request " + httpPost.getURI());
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            content = EntityUtils.toString(entity, "UTF-8");
            System.out.println("--------------------------------------");
            System.out.println("Status: " + response.getStatusLine());
            System.out.println("Response content: " + content);
            System.out.println("--------------------------------------");
        }
        // 关闭连接,释放资源
        response.close();
        httpclient.close();
        return content;
    }

    /**
     * 发送POST请求,得到二进制文件流
     * 
     * @param url
     * @param mapParams
     * @return byte[]
     */
    public static byte[] postFile(String url, Map<String, String> mapParams) {
        byte[] byteArray = null;
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();

        // 创建httpPost
        HttpPost httpPost = new HttpPost(url);

        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000 * 60).setConnectTimeout(1000 * 60)
                .build();// 设置请求和传输超时时间
        httpPost.setConfig(requestConfig);

        CloseableHttpResponse response = null;

        // 创建参数队列
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        if (mapParams != null) {
            Set<Entry<String, String>> entrySet = mapParams.entrySet();
            for (Entry<String, String> entry : entrySet) {
                formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        try {
            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httpPost.setEntity(uefEntity);
            // System.out.println("executing request " + httpPost.getURI());
            response = httpclient.execute(httpPost);// --------------
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                byteArray = EntityUtils.toByteArray(entity);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                response.close();
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return byteArray;
    }

    /**
     * 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
     * 
     * @param imgFilePath
     * @return String
     */
    public static String GetImageStr(String imgFilePath) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
        byte[] data = null;

        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgFilePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 对字节数组Base64编码;
        byte[] dataR = Base64Utils.encode(data);
        return (dataR == null || dataR.length == 0) ? "" : new String(dataR);// 返回Base64编码过的字节数组字符串
    }

    /**
     * 对字节数组字符串进行Base64解码并生成图片
     * 
     * @param imgStr
     * @param imgFilePath
     * @return boolean
     */
    public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) // 图像数据为空
            return false;
        try {
            // Base64解码
            byte[] bytes = Base64Utils.decodeFromString(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值