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);
    
        }
  • 相关阅读:
    UOJ #276. 【清华集训2016】汽水
    Luogu P4585 [FJOI2015]火星商店问题
    Luogu P5416 [CTSC2016]时空旅行
    NOIP 2011 提高组初赛错题简析
    Luogu P4068 [SDOI2016]数字配对
    UOJ Easy Round #5
    Codechef September Challenge 2019 Division 2
    Project Euler Problem 675
    AtCoder Grand Contest 037
    拿2k的前端开发都会做些什么?
  • 原文地址:https://www.cnblogs.com/ychun/p/15611685.html
Copyright © 2011-2022 走看看