Java网络编程—http请求的两种形式

本文详细介绍如何使用Java网络编程进行HTTP请求,包括GET和POST请求的实现,以及如何解析响应头和响应体。通过具体代码示例,展示如何与Tomcat服务器上的Struts2框架交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java网络编程的程序可以通过输入和输出流拿到http的响应结果和发送请求,为了测试Java网络编程中的http请求,在Tomcat服务器运行Struts2框架,定义了一个action,然后Java程序访问这个action。
Action代码

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

public class TestAction extends ActionSupport {

    private String name;
    private String password;

    public void setName(String name) {
        this.name = name;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String execute() throws Exception {
        StringBuffer requestURL = ServletActionContext.getRequest().getRequestURL();
        System.out.println(requestURL);
        ServletActionContext.getResponse().setHeader("xiaoguo","xiaoguo");
        ServletActionContext.getResponse().setContentType("html/text;charset=UTF-8");
        ServletActionContext.getResponse().getWriter().print("成功了");
        ServletActionContext.getResponse().getWriter().print(name+"--->"+password);
        System.out.println(name+"--->"+password);

        return null;
    }
}

发送Get请求

public static String DoGet() throws IOException {
        String result="";
        URL url = new URL("http://localhost:8080/test.action");

        HttpURLConnection  conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod("GET");   //设置本次请求的方式 , 默认是GET方式, 参数要求都是大写字母
        conn.setConnectTimeout(5000);//设置连接超时
        conn.setDoInput(true);//是否打开输入流 , 此方法默认为true
        conn.setDoOutput(true);//是否打开输出流, 此方法默认为false
        conn.connect();//表示连接

        //获取所有响应头字段
        Map<String, List<String>> fields = conn.getHeaderFields();
        for (String key : fields.keySet()) {
            System.out.println(key+"--->"+fields.get(key));
        }

        //定义BufferedReader输入流来读取URL的响应内容
        InputStreamReader inputStreamReader = new InputStreamReader(conn.getInputStream(), "UTF-8");

        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line;
        while((line=bufferedReader.readLine())!=null){
            result += line;
        }
        conn.disconnect();

        return result;
    }

发送Post请求

public static String DoPost() throws IOException {
        String result="";
        String param="name=xiaoguo&password=123";

        URL url = new URL("http://localhost:8080/test.action");

        HttpURLConnection  conn = (HttpURLConnection) url.openConnection();

        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

        conn.setRequestMethod("POST");   //设置本次请求的方式 , 默认是GET方式, 参数要求都是大写字母
        conn.setDoInput(true);//是否打开输入流 , 此方法默认为true
        conn.setDoOutput(true);//是否打开输出流, 此方法默认为false,Post请求必须要设置
        conn.connect();//表示连接

        //获取HttpURLConnection对象的输出流
        PrintWriter writer = new PrintWriter(conn.getOutputStream());
        //发送参数
        writer.print(param);
        //flush输出流的缓冲
        writer.flush();
        writer.close();

        //定义BufferedReader输入流来读取URL的响应内容
        InputStreamReader inputStreamReader = new InputStreamReader(conn.getInputStream(), "UTF-8");

        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line;
        while((line=bufferedReader.readLine())!=null){
            result += line;
        }
        bufferedReader.close();
        //断开连接
        conn.disconnect();

        return result;
    }

测试方法

public static void main(String[] args) {
        try {
            String s = DoGet();
            System.out.println(s);
            String s1 = DoPost();
            System.out.println(s1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

测试方法的运行结果

null--->[HTTP/1.1 200]
xiaoguo--->[xiaoguo]
Content-Length--->[21]
Date--->[Wed, 12 Dec 2018 15:55:31 GMT]
Content-Language--->[zh-CN]
Content-Type--->[html/text;charset=UTF-8]
成功了null--->null
成功了xiaoguo--->123

Process finished with exit code 0

Tomcat端打印信息

http://localhost:8080/test.action
null--->null
http://localhost:8080/test.action
xiaoguo--->123

这就说明了,我们发送get请求可以获取到响应头信息和利用输入流得到响应体信息。发送post请求可以利用输出流传参数。

!!!!
!!!!
(利用上面的post请求,还是一种暴力破解密码的方法!!)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值