Java基础学习-发送http请求

2021-12-15 20:47:16 浏览数 (1)

最近在用python做接口测试,刚好最近也在学习Java,就尝试用Java发送一下http请求~~~~~~

感觉大多数第一次尝试的时候都是用百度做测试:

向https://www.baidu.com/网址发送get请求

看代码:

get请求

代码语言:javascript复制
public class HttpURLConnectionDemo {
    //get请求
    public static void main(String[] args) {
        try {
            URL url = new URL("https://www.baidu.com/");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            int reponse = connection.getResponseCode();
            String text = connection.getResponseMessage();
            System.out.println("响应状态码为:" reponse "tmessage为:" text);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

post请求:(无参数),访问url为本地服务

代码语言:javascript复制
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

public class HttpURLConnectionDemo {

    public Map<String, List> post(){
        Map map = new HashMap();
        try{
            URL url = new URL("http://192.168.30.35:8080/api/v1/product/manager/page");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            int reponse = connection.getResponseCode();
            String text = connection.getResponseMessage();
            map.put("code",reponse);
            map.put("message",text);
//            System.out.println("响应状态码为:" reponse "tmessage为:" text);
//            System.out.println("结果为" map);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(map);
        return map;
    }

总结:

getpost请求都无参数时,区别就在于请求方法上:connection.setRequestMethod("POST");

给post请求做了一点小优化:

代码语言:javascript复制
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

public class HttpURLConnectionDemo {
    //post请求
    public Map<String, List> post(){
        Map map = null;
        try{
            URL url = new URL("http://192.168.30.35:8080/api/v1/product/manager/page");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            int reponse = connection.getResponseCode();
            String text = connection.getResponseMessage();
            map = new HashMap();
            map.put("code",reponse);
            map.put("message",text);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(map);
        return map;
    }

0 人点赞