• Java POST和GET 发送请求案例


    <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<直接上代码>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    Person(对象)

    public class Person {
        private String name;
        private Integer age;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    }

    PersonReq(请求参数对象)

    public class PersonReq {
        private String name;
        private Integer age;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    }

    DemoService(业务类)

    package com.demo;
    
    import org.springframework.stereotype.Service;
    
    import java.util.ArrayList;
    import java.util.List;
    
    @Service
    public class DemoService {
        /**
         * 获取列表
         *
         * @param personReq 对象参数
         * @return
         */
        public List<Person> personList(PersonReq personReq) {
            List<Person> list = new ArrayList<>();
            Person person = new Person();
            person.setAge(personReq.getAge());
            person.setName(personReq.getName());
            Person person1 = new Person();
            person1.setAge(20);
            person1.setName("2诗");
            list.add(person);
            list.add(person1);
            return list;
        }
    
        public List<Person> personList() {
            List<Person> list = new ArrayList<>();
            Person person = new Person();
            person.setAge(10);
            person.setName("1诗");
            Person person1 = new Person();
            person1.setAge(20);
            person1.setName("2诗");
            list.add(person);
            list.add(person1);
            return list;
        }
    }

    DemoController(控制类)

    package com.demo;
    
    import com.alibaba.fastjson.JSON;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.List;
    
    @RestController
    @RequestMapping("/demo")
    public class DemoController {
        private final Logger logger = LoggerFactory.getLogger(this.getClass());
        @Autowired
        DemoService demo;
    
        @PostMapping("/list")
        public List<Person> getPerson(@RequestBody PersonReq personReq) {
            List<Person> people = demo.personList(personReq);
            logger.info("list:{}", JSON.toJSONString(people));
            return people;
        }
    
        @GetMapping("/list1")
        public List<Person> getPerson() {
            List<Person> people = demo.personList();
            logger.info("list1:{}", JSON.toJSONString(people));
            return people;
        }
    }

    Application (启动类)

    启动项目,然后下一步,外部 就可以开始调接口了

    package com;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.scheduling.annotation.EnableScheduling;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    @EnableScheduling
    @EnableSwagger2
    @SpringBootApplication
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }

    HttpClients(工具类)

    package com.demo;
    
    import com.alibaba.fastjson.JSONObject;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    /**
     * HTTP 工具类
     */
    public class HttpClients {
        private static final Logger logger = LoggerFactory.getLogger(HttpClients.class);
    
    
        /**
         * 向指定URL发送POST方法的请求
         *
         * @param url
         * @param param
         * @param ContentType
         * @return
         */
        public static String sendPost(String url, String param, String ContentType) {
            String result = "";
            try {
                //存储请求
                PrintWriter out;
    
                //存储接口返回的response
                BufferedReader in;
    
                // 获取访问地址
                //得到网络访问对象java.net.HttpURLConnection
                URL realUrl = new URL(url);
    
                //设置请求参数,以流的形式连接
                HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
    
                //设置http的请求头
                conn.setRequestProperty("accept", "*/*");
    
                //设置请求的Contenttype
                if (ContentType == null || ContentType.equals("")) {
                    if (isJson(param)) {
                        conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
                    } else {
                        if (url.toLowerCase().contains(".asmx")) {
                            conn.setRequestProperty("Content-Type", "text/xml;charset=utf-8");
                        } else {
                            conn.setRequestProperty("Content-Type", "application/xml;charset=utf-8");
                        }
                    }
                } else {
                    conn.setRequestProperty("Content-Type", ContentType);
                }
    
                //特殊处理:如果是1.0的请求则进一步具体设定setRequestProperty,并对xml格式做优化
                if (url.toLowerCase().contains(".asmx")) {
                    if (url.toLowerCase().contains("datacomparews")) {
                        conn.setRequestProperty("SOAPAction", "http://tempuri.org/DataTableCompare");
                        String Xml = "<?xml version="1.0" encoding="utf-8"?>" +
                                "<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">" +
                                "<soap:Body>";
                        Xml += param.replace("<?xml version="1.0" encoding="UTF-8"?>", "");
                        Xml += "</soap:Body></soap:Envelope>";
                        param = Xml;
                    } else {
                        String Xml = "<?xml version="1.0" encoding="utf-8"?>" +
                                "<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">" +
                                "<soap:Body><Request xmlns="http://tempuri.org/"><requestXML>" + "<![CDATA[";
                        Xml += param.replace("<?xml version="1.0" encoding="UTF-8"?>", "");
                        Xml += "]]></requestXML></Request></soap:Body></soap:Envelope>";
                        param = Xml;
                        conn.setRequestProperty("SOAPAction", "http://tempuri.org/Request");
                    }
                }
    
                //keep-alive 发出的请求建议服务器端保留连接,这样下次向同一个服务器发请求时可以走同一个连接
                conn.setRequestProperty("connection", "Keep-Alive");
    
                //设置请求的浏览器相关属性
                conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
    
                //设定接受的返回流字节码为UTF-8
                conn.setRequestProperty("Accept-Charset", "utf-8");
                conn.setRequestProperty("Charset", "utf-8");
    
                //设置超时时间,如果未设置超时时间,但是访问超时了就会一直卡在这里
                conn.setConnectTimeout(50000 * 12);
                conn.setReadTimeout(50000 * 12);
    
                //设置是否向HttpURLConnection输出,默认为false,发送post请求的不啊必须设置为true
                conn.setDoOutput(true);
    
                //设置是否从httpUrlConnection读入,默认为true,不设置也可以
                conn.setDoInput(true);
    
                //处理输入请求 ,设置请求正文,即要提交的数据
                out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
    
                // 写入参数到请求中
                out.print(param);
    
                //flush输出流的缓冲
                out.flush();
    
                //处理输出接口,远程对象变为可用
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
    
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                result = e.getMessage();
                e.printStackTrace();
            }
            return result;
        }
    
        /**
         * 向指定URL发送GET方法的请求
         *
         * @param url 接口URL
         * @return
         */
        public static String sendGet(String url) {
            HttpURLConnection httpConn = null;
            BufferedReader in = null;
            try {
                URL realUrl = new URL(url);
    
                // 打开和URL之间的连接
                httpConn = (HttpURLConnection) realUrl.openConnection();
                // 设置通用的请求属性
                httpConn.setRequestProperty("accept", "*/*");
                httpConn.setRequestProperty("connection", "Keep-Alive");
                httpConn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
    
                //设定接受的返回流字节码为UTF-8
                httpConn.setRequestProperty("Accept-Charset", "utf-8");
                httpConn.setRequestProperty("Charset", "utf-8");
                
                httpConn.setConnectTimeout(5000);
                httpConn.setReadTimeout(5000);
                //读取响应
                if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    StringBuffer content = new StringBuffer();
                    String tempStr = "";
                    // 建立实际的连接
                    httpConn.connect();
                    // 定义 BufferedReader输入流来读取URL的响应
                    in = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
                    while ((tempStr = in.readLine()) != null) {
                        content.append(tempStr);
                    }
                    return content.toString();
                } else {
                    logger.error("request error!");
                }
            } catch (IOException e) {
                e.printStackTrace();
    
                // 使用finally块来关闭输入流
            } finally {
                try {
                    in.close();
                    httpConn.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
        /**
         * 判断字符串是不是json格式
         *
         * @param request
         * @return
         */
        private static boolean isJson(String request) {
            try {
                JSONObject.parseObject(request);
                return true;
            } catch (Exception e) {
                return false;
            }
        }
    
    
    }

    Demo1Controller(外部调用类)

    package com.demo;
    
    import com.alibaba.fastjson.JSON;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    @RequestMapping("/demo1")
    public class Demo1Controller {
        private static final Logger logger = LoggerFactory.getLogger(Demo1Controller.class);
    
        @GetMapping("/list")
        public String getPerson1() {
            PersonReq personReq = new PersonReq();
            personReq.setAge(10);
            personReq.setName("1诗");
            String url = "http://localhost:8080/demo/list";
            String result = HttpClients.sendPost(url, JSON.toJSONString(personReq), "");
            logger.info(" getPerson1 list:{}", result);
            return result;
        }
    
        /**
         * GET 测试
         *
         * @param args
         * @throws Exception
         */
        public static void main(String[] args) throws Exception {
            String url = "http://localhost:8080/demo/list1";
            String result = HttpClients.sendGet(url);
            logger.info("result:{}", result);
        }
    
    
        /**
         * POST 测试
         *
         * @param args
         * @throws Exception
         */
        /*public static void main(String[] args) {
            PersonReq personReq = new PersonReq();
            personReq.setAge(10);
            personReq.setName("1诗");
            String url = "http://localhost:8080/demo/list";
            String result = HttpClients.sendPost(url, JSON.toJSONString(personReq), "");
            logger.info("result:{}", result);
        }*/
    }

     <<<<<<<<<<<<<<<OK>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

  • 相关阅读:
    button label textfield对齐 textview UI样式
    iOS真机测试
    Android学习
    CoreMontion加速计
    一些用xib加载主界面的过程
    英特尔公司
    CISC和RISC
    Terminating app due to uncaught exception 'NSGenericException' 类崩溃文章收集
    UICollectionView 介绍 <转>
    流媒件应用FreeStreamer 学习2
  • 原文地址:https://www.cnblogs.com/weigy/p/13867969.html
Copyright © 2020-2023  润新知