• Java 发送http GET/POST请求


    最近项目里面需要用到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信息带上。

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

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

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

    超时无响应问题设置

    //连接超时 单位毫秒
    httpURLConnection.setConnectTimeout(10000);
    //读取超时 单位毫秒
    httpURLConnection.setReadTimeout(2000);
  • 相关阅读:
    daper
    存储过程事务
    dengluzhucehaiyouxianshiMVC
    遍历加监听
    类的操作
    轮播图
    定时器的应用(三)
    定时器的应用(二)
    定时器的应用(一)
    延时调用
  • 原文地址:https://www.cnblogs.com/mengw/p/11307782.html
Copyright © 2020-2023  润新知