zoukankan      html  css  js  c++  java
  • 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);
    
        }
  • 相关阅读:
    WCF与 Web Service的区别是什么?各自的优点在哪里呢?
    asp、asp.net、ado、ado.net各自区别和联系?
    SQL触发器 inset自学经验
    SQL触发器实例讲解
    特价汇9.9元商品
    sql中数据库连接与断开式连接有什么区别?
    终止线程的三种方法
    selenium设置代理,基于chrome浏览器
    Selenium Webdriver定位元素的几种方式
    spring常用接口 InitializingBean的作用
  • 原文地址:https://www.cnblogs.com/ychun/p/15611685.html
Copyright © 2011-2022 走看看