zoukankan      html  css  js  c++  java
  • post请求

    public class HttpRequest {
        
        @Test
        public void httpPost() throws IOException {
            //创建client
            CloseableHttpClient client=HttpClients.createDefault();
    
            //创建 HttpPost
            HttpPost post=new HttpPost("http://www.httpbin.org/post");
            //设置请求头
            post.setHeader("accept","application/json");
            post.setHeader("Referer","http://www.httpbin.org/");
            //设置请求参数
            StringEntity se=new StringEntity("this is request param", ContentType.APPLICATION_JSON);
            post.setEntity(se);
            //获取响应
            CloseableHttpResponse response=client.execute(post);
            HttpEntity entity=response.getEntity();
            String result=EntityUtils.toString(entity);
            //关闭流和连接
            EntityUtils.consume(entity);
            response.close();
            //解析result
            JSONObject jsonObject=JSON.parseObject(result);
            System.out.println(jsonObject.getString("data"));
    
        }
    }

      结果

    this is request param

      其中设置请求参数有两种方法

      1.使用 StringEntity ,StringEntity 的更多参数查看源码可知

    StringEntity se=new StringEntity("this is request param", ContentType.APPLICATION_JSON);
    post.setEntity(se);

      2. 使用  UrlEncodedFormEntity,UrlEncodedFormEntity 的更多参数查看源码可知

    NameValuePair nvp=new BasicNameValuePair("requestParam","this is request param");
    List<NameValuePair> nvps=new ArrayList<>();
    nvps.add(nvp);
    UrlEncodedFormEntity param=new UrlEncodedFormEntity(nvps, Charset.defaultCharset());
    post.setEntity(param);
  • 相关阅读:
    Python 基础之函数初识与函数参数
    python 基础之浅拷贝与深拷贝
    Python 基础之集合相关操作与函数和字典相关函数
    Python 基础之字符串操作,函数及格式化format
    Rocket
    Rocket
    Rocket
    Rocket
    Rocket
    Rocket
  • 原文地址:https://www.cnblogs.com/yjh1995/p/12130942.html
Copyright © 2011-2022 走看看