首页 > 代码库 > httpPost请求用java实现的方法

httpPost请求用java实现的方法

package com.day3.sample;

//首先下面我我们需要导入的jar包和文件

import java.io.IOException; import java.util.ArrayList; import java.util.List;

import org.apache.http.Consts;

import org.apache.http.NameValuePair;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.util.EntityUtils;

public class HttpClientDemo2 {

  

  //构造POST请求

  public void test_post(){

    //新建一个客户对象

    CloseableHttpClient client = HttpClients.createDefault();

    //新建一个HttpPost请求的对象 --并将uri传给这个对象

    HttpPost post = new HttpPost("http://localhost:8080/test1312/Calc");

    //使用NameValuePair  键值对  对参数进行打包

    List<NameValuePair> list = new ArrayList<NameValuePair>

    list.add(new BasicNameValuePair("a","1"));

    list.add(new BasicNameValuePair("b","2"));
  
    //4.对打包好的参数,使用UrlEncodedFormEntity工具类生成实体的类型数据

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,Consts.UTF_8);
  
    //5.将含有请求参数的实体对象放到post请求中
    post.setEntity(entity);
  
    //6.新建一个响应对象来接收客户端执行post的结果
    CloseableHttpResponse response = client.execute(post);
  
    //7.从响应对象中提取需要的结果-->实际结果,与预期结果进行对比
    if(response.getStatusLine().getStatusCode() == 200){

        System.out.println(EntityUtils.toString(response.getEntity()));

    }
  
   }

}

//编写过程中如果有异常请选择shrow这个异常

httpPost请求用java实现的方法