基于Restful形式访问远程服务并封装对象

  • 创建客户端(两种方式)
    1. 基于Httpclient
        HttpClient httpclient = HttpClients.createDefault();
        ObjectMapper object = new ObjectMapper();
        // 验证
        List<NameValuePair> requestParam = new ArrayList<NameValuePair>();
        requestParam.add(new BasicNameValuePair("参数1", "参数值"));
        requestParam.add(new BasicNameValuePair("参数2", "参数值"));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(requestParam, Consts.UTF_8);
        HttpPost httppost = new HttpPost(url);
        httppost.setEntity(entity);
        HttpResponse execute = httpclient.execute(httppost);
        InputStream content = execute.getEntity().getContent();
        BufferedReader bfr = new BufferedReader(new InputStreamReader(content));
        String s;
        while ((s = bfr .readLine()) != null) {
            System.err.println(s);
        }
    //封装成User对象
    List<User> users =object.readValue(s,new TypeReference<List<User>>(){})
    注意因为在返回的字符串中有不规则字符串,有时候封装不了,所以需要忽略其中匹配不上的字符串,那么我们需要在执行上个api直线加上
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    这个api就是糊了匹配不上的字符串
  1. 基于spring的RestTemplate请求远程服务
    RestTemplate restTemplate = new RestTemplate();
        MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
        requestEntity.add("参数1", "参数值");
        requestEntity.add("参数2", "参数值");
        String result = restTemplate.postForObject(url, requestEntity,String.class);
        MultiValueMap<String, String> host = new LinkedMultiValueMap<>();
        MultiValueMap<String, String> host = new LinkedMultiValueMap<>();
        host.add("userTokenId", result);
        String hostJson = restTemplate.postForObject(url, host, String.class);
        //封装成User对象
    List<Host> users =object.readValue(s,new TypeReference<List<Host>>(){})
    注意因为在返回的字符串中有不规则字符串,有时候封装不了,所以需要忽略其中匹配不上的字符串,那么我们需要在执行上个api直线加上
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    这个api就是糊了匹配不上的字符串

猜你喜欢

转载自blog.csdn.net/suubyy/article/details/77941690
今日推荐