パラメータを渡すためのJavaRestTemplateリモート呼び出し

パラメータを渡すためのJavaRestTemplateリモート呼び出し

最近、SpringのRestTemplateツールクラスを使用してインターフェイスを要求すると、パラメーターの受け渡しに落とし穴が見つかりました。つまり、パラメーターをMapにカプセル化すると、Mapのタイプが選択されます。RestTemplatePOSTリクエストを実装する主な方法は3つあります

  1. postForObjectメソッドを呼び出します
  2. postForEntityメソッドを使用する
  3. 交換メソッドを呼び出す

postForObjectメソッドとpostForEntityメソッドの主な違いは、postForEntityメソッドで
ヘッダープロパティを設定できることです。ヘッダープロパティ値を指定する必要がある場合は、postForEntityメソッドを使用します。

ExchangeメソッドはpostForEntityに似ていますが、より柔軟性があります。Exchangeは、get、put、およびdeleteリクエストを呼び出すこともできます。これらの3つのメソッドを使用して、postリクエストを呼び出してパラメーターを渡します。マップを次の2つのタイプとして定義することはできません(urlがパラメーターの受け渡しにプレースホルダーを使用する場合を除く)
Map<String, Object> paramMap = new HashMap<String, Object>();
Map<String, Object> paramMap = new LinkedHashMap<String, Object>();

テストの結果、これら2つのマップのパラメーターをバックグラウンドで受信できないことがわかりました。この問題により、2日間問題が発生しました。最後に、マップタイプをLinkedMultiValueMapに変更すると、パラメーターがバックグラウンドに正常に渡されました。
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
注:HashMapはリクエストの本文で渡され、MultiValueMapはフォームで渡されます。

テスト後、正しいPOSTパラメーターの受け渡し方法は次のとおりです。

public static void main(String[] args) {
        RestTemplate template = new RestTemplate();
        String url = "http://192.168.2.40:8081/channel/channelHourData/getHourNewUserData";
        // 封装参数,千万不要替换为Map与HashMap,否则参数无法传递
        MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
        paramMap.add("dt", "20180416");
 
        // 1、使用postForObject请求接口
        String result = template.postForObject(url, paramMap, String.class);
        System.out.println("result1==================" + result);
 
        // 2、使用postForEntity请求接口
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
        ResponseEntity<String> response2 = template.postForEntity(url, httpEntity, String.class);
        System.out.println("result2====================" + response2.getBody());
 
        // 3、使用exchange请求接口
        ResponseEntity<String> response3 = template.exchange(url, HttpMethod.POST, httpEntity, String.class);
        System.out.println("result3====================" + response3.getBody());
}

補足:POSTパラメーターオブジェクト

@Autowired
private RestTemplate restTemplate;
private String url="http://localhost:8080/users";
 
public Integer save(User user){
    Map<String,String> map = restTemplate.postForObject(url, user, Map.class);
    if(map.get("result").equals("success")){
        //添加成功
        return 1;
    }
    return -1;
}
 
 //这是访问的controller方法  
@RequestMapping(value = "users",method = RequestMethod.POST)
public Map<String,String> save(@RequestBody User user){
    Integer save = userService.save(user);
    Map<String,String> map=new HashMap<>();
    if(save>0){
        map.put("result","success");
        return map;
    }
    map.put("result","error");
    return map;
}

ps:postリクエストはプレースホルダー(getと同様)として渡すこともできますが、エレガントに見えません。テキストでこのメソッドを使用することをお勧めします。
パラメータ転送の説明のGETメソッド
getリクエストであり、送信のためにパラメータをマップにカプセル化する場合、マップはHashMapを使用する必要があり、URLは次のようにプレースホルダーを使用する必要があります。

public static void main(String[] args) {
        RestTemplate restTemplate2 = new RestTemplate();
        String url = "http://127.0.0.1:8081/interact/getData?dt={dt}&ht={ht}";
   
        // 封装参数,这里是HashMap
    Map<String, Object> paramMap = new HashMap<String, Object>();
    paramMap.put("dt", "20181116");
    paramMap.put("ht", "10");
 
    //1、使用getForObject请求接口
    String result1 = template.getForObject(url, String.class, paramMap);
    System.out.println("result1====================" + result1);
 
    //2、使用exchange请求接口
    HttpHeaders headers = new HttpHeaders();
    headers.set("id", "lidy");
    HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(null,headers);
    ResponseEntity<String> response2 = template.exchange(url, HttpMethod.GET, httpEntity, String.class,paramMap);
    System.out.println("result2====================" + response2.getBody());
}

RestTemplateが提供するdelete()メソッドとput()メソッドには戻り値がありませんが、呼び出したいインターフェイスには戻り値があります。インターネット上の多くの情報は、exchange()メソッドを呼び出すことによって書き込まれますが、基本的には与えられません完全な例が与えられたため、コードを参照するときにパラメーターを渡すことができないという問題が発生しました。現在問題を解決しました。次に、解決策を共有します。

これを実現するためにexchange()メソッドも使用しますが、URLはそれにこだわっています
。Exchangeメソッドを使用してgetリクエストを呼び出すように、プレースホルダーを使用してリクエストインスタンス削除する必要があります。requestメソッドはHttpMethod.DELETE(結果のスタイルはプレースホルダーを使用します)

/**
 * 删除用户
 * @param id
 * @return
 */
public String delete(Long id) {
    StringBuffer url = new StringBuffer(baseUrl)
            .append("/user/delete/{id}");
 
    Map<String, Object> paramMap = new HashMap<>();
    paramMap.put("id", id);
 
    ResponseEntity<String > response = restTemplate.exchange(url.toString(), HttpMethod.DELETE, null, String .class, paramMap);
    String result = response.getBody();
 
    return result;
}

補足:結果のスタイルの直接接続URL

//负责调用provider的方法,获取数据
@Autowired
private RestTemplate restTemplate;
//在provider端资源的路径
private String url="http://localhost:8080/details";   
 
public String deleteDetail(Integer id){
    ResponseEntity<String> response = restTemplate.exchange(url + "/" + id, HttpMethod.DELETE, null, String.class);
    String result = response.getBody();
    return result;
}
 
//被调用的controller方法
@ResponseBody
@RequestMapping(value = "details/{id}",method = RequestMethod.DELETE)
public String deleteDetail(@PathVariable Integer id){
    Integer integer = detailService.deleteDetail(id);
    if(integer>0){
        return "success";
    }
    return "error";
}

スタイルが重要でない場合は、プレースホルダーを使用できます

private String url="http://localhost:8080/details?id={id}";
 
public String deleteDetail(Integer id){
         
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("id", id);
        ResponseEntity<String > response = restTemplate.exchange(url.toString(), HttpMethod.DELETE, null, String .class, paramMap);
        String result = response.getBody();
        return result;
    }

リクエストインスタンスを配置します。リクエストメソッドはHttpMethod.PUTを使用します

/**
 * 更新用户基础信息
 * @param userInfoDTO
 * @return
 */
public String edit(UserInfoDTO userInfoDTO) {
    StringBuffer url = new StringBuffer(baseUrl)
            .append("/user/edit?tmp=1")
            .append("&id={id}")
            .append("&userName={userName}")
            .append("&nickName={nickName}")
            .append("&realName={realName}")
            .append("&sex={sex}")
            .append("&birthday={birthday}");
 
    Map<String, Object> paramMap = new HashMap<>();
    paramMap.put("userId", userInfoDTO.getId());
    paramMap.put("userName", userInfoDTO.getUserName());
    paramMap.put("nickName", userInfoDTO.getNickName());
    paramMap.put("realName", userInfoDTO.getRealName());
    paramMap.put("sex", userInfoDTO.getSex());
    paramMap.put("birthday", userInfoDTO.getBirthday());
 
    ResponseEntity<String > response = restTemplate.exchange(url.toString(), HttpMethod.PUT, null, String .class, paramMap);
    String result = response.getBody();
    return result;
 
}

exchange()パラメータオブジェクトを再度追加します。
    参照:https//www.cnblogs.com/jnba/p/10522608.html

//测试post的controller
@RequestMapping(value = "detailsPost",method = RequestMethod.POST)
public String test02(@RequestBody Detail detail){
    System.out.println("POST-"+detail);
    return "error";
}
//测试put的controller
@RequestMapping(value = "detailsPut",method = RequestMethod.PUT)
public String test03(@RequestBody Detail detail){
    System.out.println("PUT-"+detail);
    return "error";
}
//测试delete的controller
@RequestMapping(value = "detailsDelete",method = RequestMethod.DELETE)
public String test04(@RequestBody Detail detail){
    System.out.println("DELETE-"+detail);
    return "error";
}
 
 
//测试方法
public String test(){
    //put传递对象
    //String json = "{\"author\":\"zsw\",\"createdate\":1582010438846,\"id\":1,\"summary\":\"牡丹\",\"title\":\"菏泽\"}";
    //HttpHeaders headers = new HttpHeaders();
    //headers.setContentType(MediaType.APPLICATION_JSON);
    //HttpEntity<String> entity = new HttpEntity<>(json,headers);
    //ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsPut", HttpMethod.PUT, entity, String.class);
 
    //delete传递对象
    Detail detail=new Detail();
    detail.setId(1L);
    detail.setSummary("牡丹");
    detail.setTitle("菏泽");
    detail.setAuthor("zsw");
    detail.setCreatedate(new Timestamp(new Date().getTime()));
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<Detail> entity = new HttpEntity<>(detail,headers);
    ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsDelete", HttpMethod.DELETE, entity, String.class);
 
    String result = resp.getBody();
    System.out.println(result);
    return result;
}

削除要求は上記と同じですが、getが失敗し、エラー400が直接報告されます。getはこの種のパラメータ転送をサポートしていないようです。https://blog.belonk.com/c/http_resttemplate_get_with_body.htm状況はこの兄と同じですが、私は彼の解決策を理解していなかったので、兄がいる場合は、いくつかのアドバイスをしたいと思います兄さん、とてもありがたいです。

Exchange()は、プレースホルダーを使用して単一のパラメーターを渡すことができます。

 //post传递单参
//        ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsPostD?id={id}&name={name}", HttpMethod.POST, null, String.class,1,"zsw");
        //put传递单参
        Map<String,Object> map=new HashMap<>();
        map.put("id",1);
        map.put("name","zsw");
        ResponseEntity<String> resp = restTemplate.exchange("http://localhost:8080/detailsPutD?id={id}&name={name}", HttpMethod.PUT, null, String.class,map);

get、post、put、およびdeleteリクエストに共通です。

明確で直接的かつ直感的な春の公式ウェブサイトで例を参照できますhttps://docs.spring.io/spring/docs/5.1.6.RELEASE/spring-framework-reference/integration.html#rest -テンプレート-マルチパート

おすすめ

転載: blog.csdn.net/Guesshat/article/details/109549440