我必须使用URL中的JSON,我将Springboot与jackson结合使用,当我在标头中发布一些身份验证信息时,API希望我拥有所有要发送的信息SECRETKEY + ACCESSKEY +日期>
public void sendListPayload(int count, List object, String controller) throws NoSuchAlgorithmException, IOException {
Control type = Control.valueOf(controller);
String endereco = getAdress(type);
String payloadSecure = "";
RestTemplate restTemplate = new RestTemplate();
String url = "http://adress/site.php";
HttpHeaders headers;
String payload = convertListToJson(object);
headers = getHeaders(count, payload);
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(payloadSecure, headers);
String answer = restTemplate.postForObject(url, entity, String.class);
log.info(answer);
}
GetHeader
public HttpHeaders getHeaders(int sizeRecords, String payloadSecure) throws NoSuchAlgorithmException {
HttpHeaders headers = new HttpHeaders();
String signature = "";
signature = payloadSecure + SECRETKEY + ACCESSKEY + getISODate();
String fullSignature = FIRSTPAYLOAD + getISODate() + ":" + Useful.toSha(signature);
headers.add("HEADER", fullSignature);
return headers;
我要阅读的缩小的JSON将像这样
[{"relatorioID":"1852","professorID":"7","alunoID":"37","turmaID":"44","bimestre":"0","data":"2014-06-05 07:51:49","situacao":"1"},
{"relatorioID":"1854","professorID":"7","alunoID":"37","turmaID":"44","bimestre":"0","data":"2014-06-05 07:51:55","situacao":"1"}]
我已经有一个具有相同字段的对象以JSON数据实例化 我是java和springboot的新手,如何通过secretkey和accesskey?是在get mehod的标题中吗?
然后,我必须使用jackson ...将接收到的JSON转换为对象列表,以将其插入本地数据库。
答案 0 :(得分:1)
因此,重点是您需要清楚API规范,即您的API以哪种格式请求请求。无论如何,在下面的代码中回答您的问题可以帮助您在标头中发送身份验证参数并处理响应。
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.http.ResponseEntity;
//some more class import may be you need to add
try {
UriComponents uriComponents =
UriComponentsBuilder.newInstance().scheme("https").host(host).path(url).
queryParam("url_param1", value).queryParam("another_param",
value).build().encode();
HttpHeaders headers = new HttpHeaders();
headers.add("SECRETKEY", value);
HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
ResponseEntity<List<MyResponseObject>> response = restTemplate.exchange(uriComponents.toUri(), HttpMethod.GET, entity, new ParameterizedTypeReference<List<MyResponseObject>>());
List<MyResponseObject > responses= response.getBody();
} catch (Exception e) {
logger.error(e.getMessage());
}
创建MyResponseObject
类以绑定您的响应json属性
public class MyResponseObject {
@JsonProperty("relatorioID")
private String relatorioID;
@JsonProperty("professorID")
private Integer professorID;
...
//getter //setter
}
我希望这可以帮助您通过在URL中对查询参数进行编码来将您的参数绑定到标头并发送。获得响应后,将其作为MyResponseObject
对象的列表。