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

《Java核心技术 卷II》获取Web数据提交表单数据

提交表单数据

了解即可,直接上案例

package 第4章网络.post;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.Properties;
import java.util.Scanner;

public class PostTest {

    public static void main(String[] args) throws IOException {
        String propsFilename = args.length > 0 ? args[0]
                : "D:\\ChromeCoreDownloads\\eclipse-jee-2024-09-R-win32-x86_64\\eclipse\\eclipse-workspace\\JavaCore2/src/第4章网络/post/post.properties";
        var props = new Properties();
        try (Reader in = Files.newBufferedReader(Path.of(propsFilename), StandardCharsets.UTF_8)) {
            props.load(in);
        }
        String urlString = props.remove("url").toString();
        Object userAgent = props.remove("User-Agent");
        Object redirects = props.remove("redirects");
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        String result = doPost(new URL(urlString), props, userAgent == null ? null : userAgent.toString(),
                redirects == null ? -1 : Integer.parseInt(redirects.toString()));
        System.out.println(result);
    }

    public static String doPost(URL url, Map<Object, Object> nameValuePairs, String userAgent, int redirects)
            throws IOException {
        var connection = (HttpURLConnection) url.openConnection();
        if (userAgent != null)
            connection.setRequestProperty("User-Agent", userAgent);
        if (redirects > 0)
            connection.setInstanceFollowRedirects(false);
        connection.setDoOutput(true);
        try (var out = new PrintWriter(connection.getOutputStream())) {
            boolean first = true;
            for (Map.Entry<Object, Object> pair : nameValuePairs.entrySet()) {
                if (first)
                    first = false;
                else
                    out.print('&');
                String name = pair.getKey().toString();
                String value = pair.getValue().toString();
                out.print(name);
                out.print("=");
                out.print(URLEncoder.encode(value, StandardCharsets.UTF_8));
            }
        }
        String encoding = connection.getContentEncoding();
        if (encoding == null)
            encoding = "UTF-8";
        if (redirects > 0) {
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM
                    || responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
                String location = connection.getHeaderField("Location");
                if (location != null) {
                    URL base = connection.getURL();
                    connection.disconnect();
                    return doPost(new URL(base, location), nameValuePairs, userAgent, redirects - 1);
                }
            }
        } else if (redirects == 0) {
            throw new IOException("太多次重定向");
        }
        var response = new StringBuilder();
        try (var in = new Scanner(connection.getInputStream(), encoding)) {
            while (in.hasNextLine()) {
                response.append(in.nextLine());
                response.append("\n");
            }
        } catch (IOException e) {
            InputStream err = connection.getErrorStream();
            if (err == null)
                throw e;
            try (var in = new Scanner(err)) {
                response.append(in.nextLine());
                response.append("\n");
            }
        }
        return response.toString();
    }

}


http://www.kler.cn/a/515013.html

相关文章:

  • 【玩转全栈】----基于ModelForm完成用户管理页面
  • KNN的调参方法
  • C++priority_queue模拟实现
  • 我的图形布局 组织结构图布局
  • OGG 19C 集成模式启用DDL复制
  • 深圳大学-计算机系统(3)-实验三取指和指令译码设计
  • PIC单片机HEX文件格式分析
  • 人工智能学习(三)之机器学习基本概念
  • Oracle 深入学习 Part 13: Maintaining Data Integrity(数据完整性维护)
  • 如何使用 findIndex() 方法查找数组中的第一个匹配元素的索引?
  • 国产编辑器EverEdit - 快捷目录
  • 盲道人行道分割YOLOV8SEG
  • 期刊论文左下角添加通讯作者和横线的方法
  • GeoJSON 数据
  • 人源化抗体的改造方式及其优势【卡梅德生物】
  • 可以免费使用的电子杂志制作平台
  • OFD、PDF 电子签章系统处理流程
  • 大模型GUI系列论文阅读 DAY3:《GPT-4V(ision) is a Generalist Web Agent, if Grounded》
  • matlab绘图——彩色螺旋图
  • 数据结构——实验六·散列表
  • Android SystemUI——通知栏构建流程(十六)
  • GA-CNN-LSTM-Attention、CNN-LSTM-Attention、GA-CNN-LSTM、CNN-LSTM四模型多变量时序预测一键对比
  • Java菜鸟养成计划(java基础)--- java中的变量
  • C语言--数据在内存中的存储
  • Android中关于View的几种属性赋值方式
  • JVM面试题解,垃圾回收之“对象存活判断”剖析