0

我应该从在 php 上实现的服务请求信息。网址看起来像这个 POSThttp://someurl/service/r.php

Accept: application/json
Content-Type: application/x-www-form-urlencoded

根据服务文档,php服务的传入数据应该是什么样子

input_type=JSON&response_type=JSON&method=someGetMethod&r_data = [{"firt_field": "firtfieldvalue", "second_field": "secondfieldvalue"}]

要从 Spring 端实现此请求,请使用以下方法

 public String myMethod(){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        MultiValueMap<String, String> r_data = new LinkedMultiValueMap<>();
        map.put("input_type", Collections.singletonList("JSON"));
        map.put("response_type", Collections.singletonList("JSON"));
        map.put("method", Collections.singletonList("someGetMethod"));
        rest_data.put("firt_field", "firtfieldvalue");
        rest_data.put("second_field", "secondfieldvalue");
        map.put("r_data", Collections.singletonList(r_data.toString()));
        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(map, headers);
        ResponseEntity<ResponseObject> response =
                restTemplate.exchange(url,
                        HttpMethod.POST,
                        entity,
                        ResponseObject.class);
        return response.getBody().getId();
}

这种方法意味着数据将被加密并以这种形式发送{input_type =[JSON], response_type = [JSON], method = [someGetMethod], r_data = [{firt_field = [firtfieldvalue], second_field= [secondfieldvalue]}]}

事实是,MultiValueMap将数据作为列表发送,这不适合我们,在这种情况下,我尝试使用 HashMap 并添加

mappingJackson2HttpMessageConverter.setSupportedMediaTypes (Arrays.asList (MediaType.APPLICATION_FORM_URLENCODED));
   restTemplate.getMessageConverters (). add (mappingJackson2HttpMessageConverter);

数据以这种方式发送,不是以列表的形式(适合我们),而是没有加密。如何解决这个问题?

从我应该在java中实现的文档中请求php服务的方法

$ url = 'http://someurl/service/r.php';
$ a = curl_init ($ url);
curl_setopt ($ a, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ a, CURLOPT_HEADER, false);
curl_setopt ($ a, CURLOPT_POST, true);
// curl_setopt ($ a, CURLOPT_HTTPHEADER, ['Content-Type: application / x-www-form-urlencoded']);

curl_setopt ($ ch, CURLOPT_POSTFIELDS, http_build_query (array (
    'method' => "someGetMethod",
    "input_type" => "JSON",
    "response_type" => "JSON",
    "r_data" => '[
      {
          "firt_field": "firtfieldvalue",
          "second_field": "secondfieldvalue"
      },
      "YourAppName"
    ] ')));
4

0 回答 0