Java:HttpURLConnection发送GET和POST请求

简介: Java:HttpURLConnection发送GET和POST请求

发送GET请求

package demo;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;


public class HttpDemo {
    public static void main(String[] args) throws IOException {
        String url = "https://www.baidu.com/";

        // 得到connection对象
        URL httpUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
        
        //连接
        connection.connect();
        
        // 获取状态码 响应结果
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            String line = null;

            StringBuffer buffer = new StringBuffer();

            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            reader.close();

            System.out.println(buffer.toString());

        }

        // 断开连接
        connection.disconnect();

    }
}

发送POST请求

package demo;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;


public class HttpDemo {
public static void main(String[] args) throws IOException {
String url = "http://httpbin.org/post";;

//得到connection对象
URL httpUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();

//设置请求方式
connection.setRequestMethod("POST");
connection.setDoOutput(true);

// 设置请求头
connection.setRequestProperty("Accept", "/");

// 设置请求体
String body = "name=Tom&age=23";
OutputStream outputStream = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(body);
writer.close();

//连接
connection.connect();

// 获取状态码 响应结果
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

String line = null;

StringBuffer buffer = new StringBuffer();

while ((line = reader.readLine()) != null) {
buffer.append(line);
}

reader.close();

System.out.println(buffer.toString());

}

// 断开连接
connection.disconnect();

}
}


            </div>
AI 代码解读
目录
打赏
0
相关文章
Java 中InetAddress类的详解
Java 中InetAddress类的详解
154 0
【Java】Generics in Java
【Java】Generics in Java
43 0
Dating Java8系列之Java8中的流操作
Dating Java8系列之Java8中的流操作
62 0
Java 中Collections工具类的使用
Java 中Collections工具类的使用
63 0
Java:HttpURLConnection发送GET和POST请求
Java:HttpURLConnection发送GET和POST请求
267 0
Servlet—HttpServletRequest与HttpServletResponse对象常用方法
Servlet—HttpServletRequest与HttpServletResponse对象常用方法
Servlet—HttpServletRequest与HttpServletResponse对象常用方法
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等