这里用的是RestTemplate,pom依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
json工具用的阿里的fastjson,pom依赖:
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.List;
/**
* @author gbx
*/
@Service
@Log4j2
public class ServiceRequestCardServiceImpl implements ServiceRequestCardService {
@Autowired
private RestTemplate restTemplate;
@Override
public Result lossReportCard(String workId, String cardNum, String appId) {
Result result = new Result();
//添加请求体数据
JSONObject jsonObject = new JSONObject();
jsonObject.put("cusid", workId);
jsonObject.put("bindcardno", cardNum);
try {
//设置请求编码参数
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
headers.add("token", TOKEN);
HttpEntity<String> formEntity = new HttpEntity<String>(jsonObject.toString(), headers);
//发送请求
String str = restTemplate.postForEntity(URL, formEntity, String.class).getBody();
result = JSON.parseObject(str, Result.class);
if (result != null && 0 != result.getCode()){
result.setCode(500);
}
} catch (Exception e) {
throw new RenException("上游服务器请求异常");
}
return result;
}
}
其中,URL为设定的请求url的常量,Result.class为根据对方返回数据设定封装的参数接受类