1. 程式人生 > 其它 >JAVA 使用RestTemplate傳送post請求

JAVA 使用RestTemplate傳送post請求

前言 要請求的介面

1、service實現層示例程式碼

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"; @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; } }

2、service介面層

public interface TestService {
    String getData();
}

3、實體類

安利一個json轉實體類工具網站https://www.bejson.com/json2javapojo/new/

public class Wrapper {

    private String Code;
    private String Message;
    private String Data;

    public void setCode(String Code) {
        this.Code = Code;
    }
    public String getCode() {
        return Code;
    }

    public void setMessage(String Message) {
        this.Message = Message;
    }
    public String getMessage() {
        return Message;
    }

    public void setData(String Data) {
        this.Data = Data;
    }
    public String getData() {
        return Data;
    }

}

4、執行日誌如下: