zl程序教程

您现在的位置是:首页 >  Java

当前栏目

Java基础学习-发送http请求

2023-04-18 14:59:55 时间

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

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

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

看代码:

get请求

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+"	message为:"+text);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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

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+"	message为:"+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请求做了一点小优化:

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;
    }