博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java 发送http GET/POST请求
阅读量:4544 次
发布时间:2019-06-08

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

最近项目里面需要用到Java发送http请求,由于发送https请求有点复杂,暂时不考虑

HttpURLConnection

HttpURLConnection是一种多用途、轻量极的HTTP客户端,使用它来进行HTTP操作可以适用于大多数的应用程序。

HttpURLConnection是Java的标准类,它继承自URLConnection,可用于向指定网站发送GET请求、POST请求。它在URLConnection的基础上提供了如下便捷的方法:

int getResponseCode(); // 获取服务器的响应代码。String getResponseMessage(); // 获取服务器的响应消息。String getResponseMethod(); // 获取发送请求的方法。void setRequestMethod(String method); // 设置发送请求的方法。

如何使用

HTTP请求方法有8种,分别是GET、POST、DELETE、PUT、HEAD、TRACE、CONNECT 、OPTIONS。其中PUT、DELETE、POST、GET分别对应着增删改查。

GET:请求获取Request-URI所标识的资源POST:在Request-URI所标识的资源后附加新的数据HEAD:请求获取由Request-URI所标识的资源的响应消息报头PUT: 请求服务器存储一个资源,并用Request-URI作为其标识DELETE :请求服务器删除Request-URI所标识的资源TRACE : 请求服务器回送收到的请求信息,主要用于测试或诊断CONNECT: HTTP/1.1协议中预留给能够将连接改为管道方式的代理服务器。OPTIONS :请求查询服务器的性能,或者查询与资源相关的选项和需求

返回的数据格式化json   用的是 com.google.gson.*;

开始

(1)包

import com.google.gson.*;import java.io.*;import java.net.*;

(2)发送GET请求

public static JsonObject getXpath(String requestUrl) {        String res = "";        JsonObject object = null;        StringBuffer buffer = new StringBuffer();        try {            URL url = new URL(requestUrl);            HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();            System.out.println(urlCon.getResponseCode());            if (200 == urlCon.getResponseCode()) {                InputStream is = urlCon.getInputStream();                InputStreamReader isr = new InputStreamReader(is, "utf-8");                BufferedReader br = new BufferedReader(isr);                String str = null;                while ((str = br.readLine()) != null) {                    buffer.append(str);                }                br.close();                isr.close();                is.close();                res = buffer.toString();                JsonParser parse = new JsonParser();                object = (JsonObject) parse.parse(res);            } else {                throw new Exception("连接失败");            }        } catch (Exception e) {            e.printStackTrace();        }        return object;    }

(3)发送POST请求

public static JsonObject postDownloadJson(String path, String post) {        URL url = null;        try {            url = new URL(path);            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();            // 提交模式            httpURLConnection.setRequestMethod("POST");            //连接超时 单位毫秒            httpURLConnection.setConnectTimeout(10000);            //读取超时 单位毫秒            httpURLConnection.setReadTimeout(2000);            // 发送POST请求必须设置如下两行            httpURLConnection.setDoOutput(true);            httpURLConnection.setDoInput(true);            // 获取URLConnection对象对应的输出流            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());            // 发送请求参数            //post的参数 xx=xx&yy=yy            printWriter.write(post);            // 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();            JsonParser parse = new JsonParser();            return (JsonObject) parse.parse(bos.toString("utf-8"));        } catch (Exception e) {            e.printStackTrace();        }        return null;    }

如果需要用到登录情况,可以先发送登录请求保存cookie,第二次发送就可以请求了

(4)保存cookie

通过这两行代码就可以把网站返回的cookie信息存储起来,下次访问网站的时候,自动帮你把cookie信息带上。

//存储cookieCookieManager cookieManager = new CookieManager();CookieHandler.setDefault(cookieManager);

通过返回的json获取值(子节点)

JsonElement cookie = res.get("data").getAsJsonObject().get("cookie");

超时无响应问题设置

//连接超时 单位毫秒httpURLConnection.setConnectTimeout(10000);//读取超时 单位毫秒httpURLConnection.setReadTimeout(2000);

 

转载于:https://www.cnblogs.com/mengw/p/11307782.html

你可能感兴趣的文章
OJ常见问题及必须认识的对拍处理水题
查看>>
Python之路【第三篇】:Python基础(二)
查看>>
登陆官方谷歌及GMAIL的方法
查看>>
(yiyan)玩转异地恋
查看>>
谷歌Chrome浏览器开发者工具的基础功能
查看>>
字符编码
查看>>
Leetcode: Linked List Cycle
查看>>
java书籍
查看>>
MySQL++简介
查看>>
HTML5实现IP Camera网页输出 分类: HTML5 ...
查看>>
windows电脑常用必备软件
查看>>
打包部署到tomcat
查看>>
第六课 链接学习
查看>>
Mysql索引PRIMARY、NORMAL、UNIQUE、FULLTEXT 区别和使用场合
查看>>
海量积分数据实时排名算法
查看>>
SQL server Error Number
查看>>
select2 插件
查看>>
MyEclipse 中文乱码
查看>>
SpringAOP03 项目脚手架、自定义注解、织入切面、引介增强
查看>>
核心动画-关键帧动画易混淆属性记录
查看>>