Java模拟浏览器发送请求

1.什么是HTTP协议

  1.1 HTTP:超文本传输语言,位于OSI模型的应用层。

  1.2 HTTP- URL的组成部分

    https://- 协议类型

    www.bai.com-主机名

    443-端口号

    index.php-项目资源路径

    附加信息-参数

如下图所示:

  1.3 HTTP的请求类型

    GET:请求获取Request-URL所标识的资源

    POST:在Request-URL所标识的资源后附加的数据

模拟浏览器发送请求:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class RequestDemo {


    public static void main(String[] args) {

    }

    /**
     *模拟发送POST请求
     * @param httpurl 请求的统一资源定位符
     * @param cookie sessionID
     * @param parameter 附加信息
     * @return 服务器响应结果
     */
    public static String sendPost(String httpurl,String cookie,String parameter){
        InputStream is=null;
        OutputStreamWriter out=null;
        HttpURLConnection con=null;
        String result="";
        try {
            //类 URL 代表一个统一资源定位符,它是指向互联网“资源”的指针。
            URL url=new URL(httpurl);
            try {
                // 返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。
                con=(HttpURLConnection)url.openConnection();
                con.setRequestMethod("POST");
                con.setRequestProperty("Cookie",cookie);
                con.setDoOutput(true);
                con.connect();
                out=new OutputStreamWriter(con.getOutputStream(),"utf-8");
                out.write(parameter);
                out.flush();
//                获取响应的输入流
                is=con.getInputStream();
                byte[] bytes=new byte[1024];
                while(is.read(bytes)!=-1) {
                    result=new String(bytes,0,bytes.length,"UTF-8");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (is!=null){
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        if (out!=null){
                            try {
                                out.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }finally {
                                if(con!=null){
                                    con.disconnect();
                                }
                            }
                        }
                    }
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return  result;
    }
}
原文地址:https://www.cnblogs.com/cw1886/p/9450052.html