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);
posted @   hjy1995  阅读(324)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示