用Java代码实现发送post请求,RestTemplate发送post请求,Httpclient发送post请求

一、JAVA 使用RestTemplate发送post请求

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;



@Service
@Slf4j
public class TestServiceImpl implements TestService {

    @Autowired
    private RestTemplate restTemplate;

    private final String URL = "http://15.15.82.127:8124/api/test/getData";

    private final String USER_NAME = "test";

    private final String PASS_WORD = "test123";
第一种方法
//RestTemplate发送POST请求之带header,入参为json格式
@Override
    public String getData(){
        //1、构建body参数
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("UserName",USER_NAME);
        jsonObject.put("Password",PASS_WORD);

        //2、添加请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type","application/json");

        //3、组装请求头和参数
        HttpEntity<String> formEntity = new HttpEntity<String>(JSON.toJSONString(jsonObject), headers);

        //4、发起post请求
        ResponseEntity<String> stringResponseEntity = null;
        try {
            stringResponseEntity = restTemplate.postForEntity(URL, formEntity, String.class);
            log.info("ResponseEntity----"+stringResponseEntity);
        } catch (RestClientException e) {
            e.printStackTrace();
        }

        //5、获取http状态码
        int statusCodeValue = stringResponseEntity.getStatusCodeValue();
        log.info("httpCode-----"+statusCodeValue);

        //6、获取返回体
        String body = stringResponseEntity.getBody();
        log.info("body-----"+body);

        //7、映射实体类
        Wrapper wrapper = JSONObject.parseObject(body, Wrapper.class);
        String data = wrapper.getData();
        log.info("data-----"+data);

        return data;
    }


第二种方法
//RestTemplate发送POST请求之formData形式
    @Override
    public String getData2(){
        MultiValueMap<String, Object> reqMap = new LinkedMultiValueMap<>();;
        reqMap.add("name","huhansan");
        reqMap.add("sex","man");
//.postForEntity(url,请求数据,返回数据类型)
        return restTemplate.postForEntity("http://localhost:8888/postwithpara", reqMap, String.class).getBody();

    }

}

restTemplate的详细用法可以见此链接 

二、Java 使用Httpclient发送post请求

    public void post(String url, Map<String, Object> params) {

        //创建httppost对象
        HttpPost post = new HttpPost(url);
        String paramStr = JSON.toJSONString(params);
        StringEntity stringEntity = new StringEntity(paramStr, StandardCharsets.UTF_8);

        //请求参数
        post.setEntity(stringEntity);

        //请求头
        post.setHeader("Content-Type", "application/json;charset=UTF-8");
        String msg = null;
        InetAddress ipaddr;
        try {

            //设置长/短连接 此处为短连接
            post.setHeader(HttpHeaders.CONNECTION, HTTP.CONN_CLOSE);

            //通过hostname获取本机ip地址
            ipaddr = InetAddress.getLocalHost();
            post.addHeader(new BasicHeader("API-RemoteIP", ipaddr.getHostAddress()));

            //创建httpclient对象发送post请求
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse resp = httpClient.execute(post);

            try {

                //返回信息
                HttpEntity entity = resp.getEntity();

                //获取请求状态码
                int statusCode = resp.getStatusLine().getStatusCode();
                if (entity != null) {
                    msg = EntityUtils.toString(entity);

                     //输出日志
                    logger.info("url:" + url + "参数:" + params.toString() + "返回信息:" + msg);
                }
                if (statusCode != 200 && statusCode != 302) {

                     //输出日志
                    logger.info("url:" + url + "失败信息:" + msg);
                }
            } finally {
                resp.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            post.reset();
            post.releaseConnection();
        }
    }

  • 4
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是使用Apache HttpClient发送POST请求的示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class HttpClientExample { public static void main(String[] args) { // 创建HttpClient实例 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpPost请求实例 HttpPost httpPost = new HttpPost("http://example.com/api"); // 设置请求头信息 httpPost.setHeader("Content-Type", "application/json"); // 设置请求体信息 String requestBody = "{\"name\": \"John\", \"age\": 30}"; StringEntity requestEntity = new StringEntity(requestBody, "UTF-8"); httpPost.setEntity(requestEntity); // 发送POST请求并获取响应 CloseableHttpResponse response = null; try { response = httpClient.execute(httpPost); // 获取响应实体 HttpEntity responseEntity = response.getEntity(); // 打印响应状态码 System.out.println(response.getStatusLine().getStatusCode()); // 打印响应内容 System.out.println(EntityUtils.toString(responseEntity)); } catch (IOException e) { e.printStackTrace(); } finally { try { if (response != null) { response.close(); } httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } } ``` 注意:在使用HttpClient发送POST请求时,需要设置请求头信息和请求体信息。请求头信息可以根据实际情况设置,请求体信息一般为JSON格式的字符串。需要注意的是,请求体字符串需要使用StringEntity类进行包装。在发送POST请求后,需要关闭响应和HttpClient实例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

等到鸡吃完米

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值