当前位置: 首页 > news >正文

Java 基于原生HttpURLConnection ,调用GET 和 POST请求 工具类

 用的是java自带的HttpURLConnection,可以脱离框架使用(除了post请求传json时用了一下json的序列化相关的jar)。

工具类代码:


import com.alibaba.fastjson.JSON;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;



/**
 * @Author : JCccc
 * @CreateTime : 2019/5/11
 * @Description :
 **/
public class HttpURLConnectionUtil {


    /**
     * get请求
     *
     * @param path
     * @param param
     * @return
     */
    public static String get(String path,Map<String, Object> param) {
        try {
            if (param != null) {
                StringBuffer paramBuffer = new StringBuffer();
                int i = 0;
                for (String key : param.keySet()) {
                    if (i == 0)
                        paramBuffer.append("?");
                    else
                        paramBuffer.append("&");
                    paramBuffer.append(key).append("=").append(param.get(key));
                    i++;
                }
                path += paramBuffer;
            }
            URL url = new URL(path);    // 把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("失败!");
            return null;
        }
    }
    /**
     * post    请求
     *
     * @param path
     * @param jsonStr
     * @return
     */
    public static String post(String path,String jsonStr) {

        try {
            URL url =  new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
            httpURLConnection.setReadTimeout(10000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");

//			PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
//			printWriter.write(postContent);
//			printWriter.flush();

            httpURLConnection.connect();
            OutputStream os=httpURLConnection.getOutputStream();
            os.write(jsonStr.getBytes("UTF-8"));
            os.flush();

            StringBuilder sb = new StringBuilder();
            int httpRspCode = httpURLConnection.getResponseCode();
            if (httpRspCode == HttpURLConnection.HTTP_OK) {
                // 开始获取数据
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {

        Map<String,Object> map=new HashMap<>();
        map.put("A","a");
        map.put("B",100);
        String getResult = get("http://192.xxx.xx.xx:8665/testGet", map);
        System.out.println(getResult);

        String postResult = post("http://192.xxx.xx.xx:8665/testPost", JSON.toJSONString(map));
        System.out.println(postResult);


    }
}

 

相关文章:

  • Java 识别请求来自移动端还是电脑端
  • MySql 别犯糊涂了! LEFT JOIN 的 ON 后接上筛选条件,多个条件会出事!
  • 微服务 分布式事务解决方案
  • MySql 索引失效、回表解析
  • Springboot 超简单实现在线预览,Word文档 doc、xlsx、pdf、txt等
  • Java 结合实例学会使用 静态代理、JDK动态代理、CGLIB动态代理
  • Springboot 实现 上传、下载 以及解决必须项目重启才能访问资源的问题
  • JAVA 获取微信用户信息,看完这篇你必须得学会
  • Java 求助! 为什么我拿不到错误信息,e.getMessage()
  • Java 获取范围内的随机整数
  • Xshell6 提示更新,使用不了! 解决方案
  • Springboot 前端请求的每次sessionid 都不同
  • Springboot mavne项目多模块打包,报错 找不到 base包,找不到common类等等
  • 浅谈乐观锁的设计
  • Mysql 唯一索引的字段值 允许多个NULL值存在吗
  • [PHP内核探索]PHP中的哈希表
  • 【407天】跃迁之路——程序员高效学习方法论探索系列(实验阶段164-2018.03.19)...
  • 8年软件测试工程师感悟——写给还在迷茫中的朋友
  • Android 初级面试者拾遗(前台界面篇)之 Activity 和 Fragment
  • Codepen 每日精选(2018-3-25)
  • ECMAScript6(0):ES6简明参考手册
  • HashMap ConcurrentHashMap
  • jquery ajax学习笔记
  • Linux CTF 逆向入门
  • mysql_config not found
  • Redis在Web项目中的应用与实践
  • Spring核心 Bean的高级装配
  • 分布式熔断降级平台aegis
  • 将 Measurements 和 Units 应用到物理学
  • 设计模式 开闭原则
  • 使用 Docker 部署 Spring Boot项目
  • 适配iPhoneX、iPhoneXs、iPhoneXs Max、iPhoneXr 屏幕尺寸及安全区域
  • 数据结构java版之冒泡排序及优化
  • 物联网链路协议
  • ​LeetCode解法汇总518. 零钱兑换 II
  • #HarmonyOS:Web组件的使用
  • $.extend({},旧的,新的);合并对象,后面的覆盖前面的
  • (02)Hive SQL编译成MapReduce任务的过程
  • (07)Hive——窗口函数详解
  • (k8s中)docker netty OOM问题记录
  • (SpringBoot)第七章:SpringBoot日志文件
  • (动态规划)5. 最长回文子串 java解决
  • (附源码)ssm码农论坛 毕业设计 231126
  • (七)微服务分布式云架构spring cloud - common-service 项目构建过程
  • (学习日记)2024.01.09
  • (一)使用IDEA创建Maven项目和Maven使用入门(配图详解)
  • (转)从零实现3D图像引擎:(8)参数化直线与3D平面函数库
  • (轉貼) 蒼井そら挑戰筋肉擂台 (Misc)
  • **CI中自动类加载的用法总结
  • .htaccess配置常用技巧
  • .net 中viewstate的原理和使用
  • .NET 中让 Task 支持带超时的异步等待
  • .Net下使用 Geb.Video.FFMPEG 操作视频文件
  • .NET中的Event与Delegates,从Publisher到Subscriber的衔接!
  • /etc/sudoer文件配置简析