博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
httpURLConnection-网络请求的两种方式-get请求和post请求
阅读量:3528 次
发布时间:2019-05-20

本文共 2263 字,大约阅读时间需要 7 分钟。

GET请求

 

/**     * 从网络获取json数据,(String byte[})      * @param path     * @return     */    public static String getJsonByInternet(String path){        try {            URL url = new URL(path.trim());            //打开连接            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();            if(200 == urlConnection.getResponseCode()){                //得到输入流                InputStream is =urlConnection.getInputStream();                ByteArrayOutputStream baos = new ByteArrayOutputStream();                byte[] buffer = new byte[1024];                int len = 0;                while(-1 != (len = is.read(buffer))){                    baos.write(buffer,0,len);                    baos.flush();                }                return baos.toString("utf-8");            }        }  catch (IOException e) {            e.printStackTrace();        }        return null;    }
POST请求
 

 

//获取其他页面的数据    /**     * POST请求获取数据     */    public static String postDownloadJson(String path,String post){        URL url = null;        try {            url = new URL(path);            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();            httpURLConnection.setRequestMethod("POST");// 提交模式            // conn.setConnectTimeout(10000);//连接超时 单位毫秒            // conn.setReadTimeout(2000);//读取超时 单位毫秒            // 发送POST请求必须设置如下两行            httpURLConnection.setDoOutput(true);            httpURLConnection.setDoInput(true);            // 获取URLConnection对象对应的输出流            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());            // 发送请求参数            printWriter.write(post);//post的参数 xx=xx&yy=yy            // flush输出流的缓冲            printWriter.flush();            //开始获取数据            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());            ByteArrayOutputStream bos = new ByteArrayOutputStream();            int len;            byte[] arr = new byte[1024];            while((len=bis.read(arr))!= -1){                bos.write(arr,0,len);                bos.flush();            }            bos.close();            return bos.toString("utf-8");        } catch (Exception e) {            e.printStackTrace();        }        return null;    }

转载地址:http://zfuhj.baihongyu.com/

你可能感兴趣的文章
Elastic Stack简介
查看>>
关于deepin系统安装design compiler的问题解答
查看>>
Java Agent简介及使用Byte Buddy和AspectJ LTW监控方法执行耗时
查看>>
记录一下最近的学习经历
查看>>
hadoop3.0+spark2.0两台云服务器集群环境配置。
查看>>
记第一次面试经历
查看>>
网站实现qq登录(springboot后台)
查看>>
简单的用户头像修改功能(springboot后台)
查看>>
springboot+mybatis实现分页
查看>>
leetcode332. 重新安排行程
查看>>
为什么局域网网段不同不能通信?
查看>>
itchat微信助手,kaggle 电影数据集分析,基于内容的电影推荐
查看>>
认识和使用JWT
查看>>
通过springboot框架,自己动手实现oauth2.0授权码模式认证
查看>>
条件表达式于运算符的点点滴滴的积累
查看>>
最短路径最基本的三种算法【此后无良辰】
查看>>
class的点点滴滴的总结
查看>>
vector 的点点滴滴的总结
查看>>
测试用例
查看>>
自动化测试学习步骤
查看>>