• HttpClient发送Post与Get请求


    发送Post请求

    public class PostDemo {
    
    
        public static void main(String[] args) throws IOException {
            //请求URL
            String url = "";
    
            //请求方式
            HttpPost post = new HttpPost(url);
    
            //请求参数
            String  param1 = "";
            String  param2 = "";
            List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
            parameters.add(new BasicNameValuePair("param1",param1));
            parameters.add(new BasicNameValuePair("param2",param2));
            //请求头
            post.setEntity(new UrlEncodedFormEntity(parameters,"utf-8"));
            //发起请求
            HttpClient client = HttpClients.createDefault();
            HttpResponse httpResponse = client.execute(post);
            //返回结果
            /**响应报文:
             状态行=http version + status code + reason phrase (HTTP/1.1 200 ok)
             响应头(k-v格式):服务器类型+日期+长度+内容类型+内容长度等等。
             相应正文:服务器返回的html页面或者json数据**/
            //状态行,状态码
            int code = httpResponse.getStatusLine().getStatusCode();
            System.out.println(code);
            HttpEntity entity = httpResponse.getEntity();
            System.out.println(entity);
            //响应正文
            String result = EntityUtils.toString(httpResponse.getEntity());
            System.out.println(result);
    
        }

    发送Get请求

    public class GetDemo {
    
    
        public static void main(String[] args) throws IOException {
            //请求URL
            String url = "";
    
            //请求参数
            String  param1 = "";
            String  param2 = "";
            url = url+"?"+param1+"="+param1+"&"+param2+"="+param2;
            //请求方式
            HttpGet get = new HttpGet(url);
            //发起请求
            HttpClient client = HttpClients.createDefault();
            HttpResponse httpResponse = client.execute(get);
            //返回结果
            //状态行,状态码
            int code = httpResponse.getStatusLine().getStatusCode();
            System.out.println(code);
            //响应正文
            String result = EntityUtils.toString(httpResponse.getEntity());
            System.out.println(result);
    
        }
  • 相关阅读:
    2021.07.01 学习总结
    2021.06.30 学习总结
    2021.06.29 学习总结
    2021.06.28 学习总结
    ubuntu 安装nginx报错./configure: error: SSL modules require the OpenSSL library
    Docker 启动alpine镜像中可执行程序文件遇到 not found
    docker基于cenots7 制作nginx镜像
    【Linux报错】VM虚拟机的CentOS7系统启动时报Generating /run/initramfs/rdsosreport.txt
    Docker Swarm 集群概念扩展
    Docker Swarm 集群弹性、动态扩缩容
  • 原文地址:https://www.cnblogs.com/ychun/p/15611685.html
Copyright © 2020-2023  润新知