restTemplate发布Post、Get请求,包含数据和文件

1.发布简单数据请求

POST

@Autowired

private RestTemplaterestTemplate;

//接口

public JSONObject login(String userName, String password){

        String url ="第三方地址";

        HttpHeaders headers =new HttpHeaders();

        //headers.setContentType(multipart/form-data);  下面两个是模拟ajax的请求头

        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        headers.set("X-Requested-With","XMLHttpRequest");

        //headers.set("Content-Type","multipart/form-data");

        MultiValueMap map =new LinkedMultiValueMap<>();

        map.add("username", userName);

        map.add("password", password);

        //map 为请求体,headers为请求头

        HttpEntity> request =new HttpEntity<>(map, headers);

        //String result = restTemplate.postForEntity(url,request,String.class);

        ResponseEntity responseEntity =restTemplate.postForEntity(url,request,String.class);

        JSONObject resutl = responseEntity.getBody();        //直接返回json数据

        String body = responseEntity.getBody(); // 获取响应体

        HttpStatus status = responseEntity.getStatusCode(); //获取响应码

        int statusCodeValue = responseEntity.getStatusCodeValue();  //获取响应值码

        HttpHeaders responsHeaders = responseEntity.getHeaders();  //获取响应头

        return responseEntity;

}

GET

//获取信息

public JSONObject userInfo(String userId){

        String url ="地址";

            //请求参数

        Map map =new HashMap<>();

        map.put("userId",userId);

        //在url中拼接参数,然后由spring从map中将值替换

        JSONObject result =restTemplate.getForObject(url +"?userId={userId}",JSONObject.class,map);

        return result;

}

2.发布带文件数据的请求

方法一:

        使用ByteArrayResource,发送字节数组。重写ByteArrayResource的getFilename。

        String httpMethod = "地址";

        RestTemplate restTemplate = new RestTemplate();

        String args = "";

        MultiValueMap paramMap = new LinkedMultiValueMap<>();

        paramMap.add("args", args);

        paramMap.add("sign", "");

        File file=new File("文件路径");

        byte[] bytesArray = new byte[(int) file.length()];

        FileInputStream fis = new FileInputStream(file);

        fis.read(bytesArray); //read file into bytes[]

        fis.close();

        ByteArrayResource contentsAsResource = new ByteArrayResource(bytesArray) {

                @Override

                public String getFilename() {

                        return "img";

                }

        };

        paramMap.add("img", contentsAsResource);

        JSONObject json = restTemplate.postForObject(httpMethod, paramMap, JSONObject.class);

        System.out.println("post json : " + json);


方法二:

        使用FileSystemResource方法。

        RestTemplate restTemplate = new RestTemplate();

        String url = "地址";

        String filePath = "文件地址";

        File file = new File(filePath);

        //文件必须封装成FileSystemResource这个类型后端才能收到附件

        FileSystemResource resource = new FileSystemResource(file);

        //将所有需要上传的参数封装到MultiValueMap里面

        MultiValueMap map = new LinkedMultiValueMap<>();

        map.add("file", resource);

        //下面这行是用来传输多个文件的

        map.add("files", new FileSystemResource[]{resource, resource});

        map.add("key1", "非文件参数key1");

        map.add("key2", "非文件参数key2"); 

        //调用接口

        restTemplate.postForEntity(url, map, String.class);

        补充:从服务端接收参数,直接接收即可。(实测有效)


方法三:(转载(有问题))

        使用使用ByteArrayResource,发送字节数组,不用FileSystemResource(发送磁盘上的文件)

        这里使用的是filename不是filepath

        MultiValueMap map = new LinkedMultiValueMap();

        final String filename="somefile.txt";

        map.add("name", filename);

        map.add("filename", filename);

        ByteArrayResource contentsAsResource = new ByteArrayResource(content.getBytes("UTF-8")){

                    @Override

                    public String getFilename(){

                        return filename;

                    }    

          };

        map.add("file", contentsAsResource);

        String result = restTemplate.postForObject(urlForFacade, map, String.class);

        补充:重写ByteArrayResource的getFilename,防止空指针异常,

方法四:(自己写的从外界接收文件发送请求,未测试) 

        结合方法二和Java实现文件传输,使用ByteArrayResource,然后通过获取文件名称。(有问题)

/***

    * 进行文件上传处理

*@paramfile

*@paramparam1

*@paramparam2

*@return

    */

publicbooleanuploadFile(MultipartFile file,Stringparam1,Stringparam2)

    {

        Stringurl="http://"+servicename"/file/upload";

        try{

                //return restTemplate.

                MultiValueMap param =newLinkedMultiValueMap<>();

                param.add("param1", param1);

                param.add("param2", param2);

                param.add("files",file.getResource());

                HttpHeaders headers =newHttpHeaders();

                headers.setContentType(MediaType.MULTIPART_FORM_DATA);

                HttpEntity> httpEntity =newHttpEntity<>(param, headers);

                ResponseEntity re = restTemplate.postForEntity(url,httpEntity,String.class);

你可能感兴趣的:(restTemplate发布Post、Get请求,包含数据和文件)