• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

yxchun

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

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);

    }

 

posted on 2021-11-27 13:24  yxchun  阅读(205)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3