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);
  • 相关阅读:
    Asp.Net基础 9.Web开发原则
    JavaScript – 1.事件 + 2.变量 + 3.判断变量初始化 + 4.函数的声明 + 5.匿名函数
    DOM – 3.window对象的属性
    Dom – 1.window对象事件 + 2.body、document对象的事件
    faint
    开会
    it's over
    so funny
    no topic
    震惊:有良医生揭无良献血内幕!
  • 原文地址:https://www.cnblogs.com/yjh1995/p/12130942.html
Copyright © 2011-2022 走看看