常用发送HTTP请求公共类

实际开发过程中常用的http请求:GET,POST

package com.demo.springbootweb.util;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
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 java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 发送 url请求 get post
 * 请求 微信小程序
 */
public class UrlUtils {

    /**
     * 发送get请求 带参数
     * @param url
     * @param param
     * @return
     */
    public static String sendGet(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * 发送get请求 无参数
     * @param url
     * @return
     */
    public static String sendGet(String url) {
        return sendGet(url, null);
    }

    /**
     * 发送post请求 有参数
     * @param url
     * @param param
     * @return
     */
    public static String sendPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    /**
     * 发送post请求 无参数
     * @param url
     * @return
     */
    public static String sendPost(String url) {
        return sendPost(url, null);
    }

    /**
     * 发送post请求 有参数 json
     * @param url
     * @param json
     * @return
     */
    public static String sendPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    /**
     * 发送post请求 有参数 json
     * @param url
     * @param json
     * @return
     */
    public static byte[] sendPostJson2(String url, String json) {
        InputStream inputStream = null;
        byte[] data = null;
        // 创建默认的CloseableHttpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(url);
        httppost.addHeader("Content-type", "application/json; charset=utf-8");
        httppost.setHeader("Accept", "application/json");
        try {
            StringEntity s = new StringEntity(json, Charset.forName("UTF-8"));
            s.setContentEncoding("UTF-8");
            httppost.setEntity(s);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                // 获取相应实体
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    inputStream = entity.getContent();
                    data = readInputStream(inputStream);
                }
                return data;
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return data;
    }

    /**
     * 将流 保存为数据数组
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        // 创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        // 每次读取的字符串长度,如果为-1,代表全部读取完毕
        int len = 0;
        // 使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            // 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        // 关闭输入流
        inStream.close();
        // 把outStream里的数据写入内存
        return outStream.toByteArray();
    }

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
----------Database-------------- 1.DataTable帮助(DataTableHelper.cs) 2.Access数据库文件操作辅助(JetAccessUtil.cs) 5.查询条件组合辅助(SearchCondition.cs) 6.查询信息实体(SearchInfo.cs) 8.Sql命令操作函数(可用于安装程序的时候数据库脚本执行)(SqlScriptHelper.cs) ----------Device-------------- 声音播放辅助(AudioHelper.cs) 摄像头操作辅助,包括开启、关闭、抓图、设置等功能(Camera.cs) 提供用于操作【剪切板】的方法(ClipboardHelper.cs) 获取电脑信息(Computer.cs) 提供用户硬件唯一信息的辅助(FingerprintHelper.cs) 读取指定盘符的硬盘序列号(HardwareInfoHelper.cs) 提供访问键盘当前状态的属性(KeyboardHelper.cs) 全局键盘钩子。这可以用来在全球范围内捕捉键盘输入。(KeyboardHook.cs) 模拟鼠标点 击(MouseHelper.cs) 全局鼠标钩子。这可以用来在全球范围内捕获鼠标输入。(MouseHook.cs) MP3文件播放操作辅助(MP3Helper.cs) 关联文件(ExtensionAttachUtil.cs) 注册文件关联的辅助(FileAssociationsHelper.cs) 打开、保存文件对话框操作辅助(FileDialogHelper.cs) 常用的文件操作辅助FileUtil(FileUtil.cs) INI文件操作辅助(INIFileUtil.cs) 独立存储操作辅助(IsolatedStorageHelper.cs) 序列号操作辅助(Serializer.cs) 获取一个对象,它提供用于访问经常引用的目录的属性。(SpecialDirectories.cs) 简单的Word操作对象(WordCombineUtil.cs) 这个提供了一些实用的方法来转换XML和对象。(XmlConvertor.cs) XML操作(XmlHelper.cs) ----------Format-------------- 参数验证的通用验证程序。(ArgumentValidation.cs) 这个提供了实用方法的字节数组和图像之间的转换。(ByteImageConvertor.cs) byte字节数组操作辅助(BytesTools.cs) 处理数据型转换,数制转换、编码转换相关的(ConvertHelper.cs) CRC校验辅助(CRCUtils.cs) 枚举操作公共(EnumHelper.cs) 身份证操作辅助(IDCardHelper.cs) 检测字符编码的(IdentifyEncoding.cs) RGB颜色操作辅助(MyColors.cs) 日期操作(MyDateTime.cs) 转换人民币大小金额辅助(RMBUtil.cs) 常用的字符串常量(StringConstants.cs) 简要说明TextHelper。(StringUtil.cs) 获取中文字首字拼写,随机发生器,按指定概率随机执行操作(Util.cs) 各种输入格式验证辅助(ValidateUtil.cs) ----------Network-------------- Cookie操作辅助(CookieManger.cs) FTP操作辅助(FTPHelper.cs) HTML操作HttpHelper.cs) 网页抓取帮助(HttpWebRequestHelper.cs) Net(NetworkUtil.cs) IE代理设置辅助(ProxyHelper.cs) ----------Winform-------------- 跨线程的控件安全访问方式(CallCtrlWithThreadSafety.cs) CheckBoxList(CheckBoxListUtil.cs) 窗口管理(ChildWinManagement.cs) 由马丁·米勒http://msdn.microsoft.com/en-us/library/ms996492.aspx提供一个简单的方法打印工作的一个RichTextBox一个帮手(ExRichTextBoxPrintHelper.cs) 显示,隐藏或关闭动画形式。(FormAnimator.cs) 对窗体进行冻结、解冻操作辅助(FreezeWindowUtil.cs) 窗体全屏操作辅助(Ful

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值