springboot 网络请求方法汇总 post

springboot的网络请求方法,post请求,带参,带header

一. RestTemplate

1. 返回数据类:

public class ResultVO<T> {
    private Integer code;
    private String msg;
    private T result;

    public ResultVO() {
    }

    public ResultVO(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public ResultVO(Integer code, String msg, T result) {
        this.code = code;
        this.msg = msg;
        this.result = result;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getResult() {
        return result;
    }

    public void setResult(T result) {
        this.result = result;
    }
}

2. 公共方法:

public class Utils {
    /*
    * 向目的URL发送post请求
    *
    * */
    public static ResultVO sendPostRequest(String url, MultiValueMap<String,String> params) {
        RestTemplate client = new RestTemplate();
        client.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type","application/json;charset=UTF-8");
        headers.set("accessToken", "*******");
        headers.set("clientInfo","{" +
                "        \"version\": \"6.22.3 \"," +
                "        \"client\": \"iOS;iPhone XS Max;13.6.0\"" +
                "      }");
        HttpMethod method = HttpMethod.POST;
        //以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //将请求头部和参数合成一个请求
        System.out.println("params===="+ params);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求,将返回的结构使用RestVO类格式化
        ResponseEntity<ResultVO> response = client.exchange(url, method, requestEntity, ResultVO.class);
        System.out.println("response=="+response.toString());
        return response.getBody();
    }

    /*
    * postForEntity请求
    *
    * */
    public static ResultVO sendPostRequest1(String url, MultiValueMap<String,String> params) {
        RestTemplate client = new RestTemplate();
        client.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type","application/json;charset=UTF-8");
        headers.set("accessToken", "*******");
        headers.set("clientInfo","{" +
                "        \"version\": \"6.22.3 \"," +
                "        \"client\": \"iOS;iPhone XS Max;13.6.0\"" +
                "      }");
        HttpMethod method = HttpMethod.POST;
        //以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //将请求头部和参数合成一个请求
        System.out.println("params===="+ params);
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
//        //执行HTTP请求,将返回的结构使用RestVO类格式化
        ResponseEntity<ResultVO> response = client.postForEntity("http://10.***.**.**:8085/postTest",requestEntity,ResultVO.class);
        System.out.println("response=="+response.toString());
        return response.getBody();
    }
}

3. TaskService

@Service
public class TaskInfoServiceImpl {

    public List<TaskInfo> getTaskInfo(String typeIds, String userId) {
        String url = "http://**.**.**.***:1616/api/Task/getList";
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("typeId", typeIds);
        params.add("userId", userId);
        //发送Post数据并返回数据
        ResultVO resultVO = Utils.sendPostRequest1(url, params);
        if (resultVO.getCode() != 200) {//进行异常处理
            System.out.println("111111111111111");
        }
        System.out.println("111111"+resultVO.getResult());
        return (List<TaskInfo>) resultVO.getResult();
    }
}

4. 调用:

public class IndexController {
    @Autowired
    TaskInfoServiceImpl taskInfoService;
    @Autowired
    TaskService taskService;

    /*
     * 根据typeId和userId获取任务列表,并插入数据库
     * 传递过来的参数是HttpServletRequest,需要另外处理
     * */
    @RequestMapping("/getTasks")
    @ResponseBody
    public ResultVO getTaskList(HttpServletRequest request) {
        ServletInputStream is = null;
        try {
            is = request.getInputStream();
            StringBuilder sb = new StringBuilder();
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = is.read(buf)) != -1) {
                sb.append(new String(buf, 0, len));
            }
            System.out.println(sb.toString());
            JsonObject returnData = new JsonParser().parse(sb.toString()).getAsJsonObject();
            String typeId =returnData.getAsJsonPrimitive("typeId").getAsString();
            String userId =returnData.getAsJsonPrimitive("userId").getAsString();
            List<TaskInfo> taskInfoList;
            taskInfoList = taskInfoService.getTaskInfo(typeId, userId);
            //反序列化成对象
            ObjectMapper mapper = new ObjectMapper();
            List<TaskInfo> list = mapper.convertValue(taskInfoList, new TypeReference<List<TaskInfo>>() { });
            // 将查询到的数据插入数据库
            for(int i=0;i<list.size(); i++) {
                taskService.save(convertTask(list.get(i),userId));
            }
            return new ResultVO(200, "登录成功", taskInfoList);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /*
     * 根据typeId和userId获取任务列表
     * 传递过来的参数是Map
     * */
    @RequestMapping("/getTasksParam")
    @ResponseBody
    public ResultVO getTaskListNew(@RequestBody Map params) {
        List<TaskInfo> taskInfoList;
        System.out.println("typeId="+params);
        String typeId = params.get("typeId").toString();
        String userId = params.get("userId").toString();
        taskInfoList = taskInfoService.getTaskInfo(typeId, userId);
        return new ResultVO(200, "登录成功", taskInfoList);

    }

    /*
    * 获取任务列表,不传参的情况
    * */
    @RequestMapping(value = "/getTaskList")
    @ResponseBody
    public ResultVO getTasks() {
        List<TaskInfo> taskInfoList;
        String typeId = "*****";
        String userId = "****";
        taskInfoList = taskInfoService.getTaskInfo(typeId, userId);
        //反序列化成对象
        ObjectMapper mapper = new ObjectMapper();
        List<TaskInfo> list = mapper.convertValue(taskInfoList, new TypeReference<List<TaskInfo>>() { });
        for(int i=0;i<list.size(); i++) {
            taskService.save(convertTask(list.get(i),userId));
        }
        return new ResultVO(200, "登录成功", taskInfoList);
    }

    /*
    * 从数据库中查询数据
    *
    * */
    @RequestMapping(value = "/getTasksLocal")
    @ResponseBody
    public ResultVO getTasksFromLocal(@RequestBody Map params) {
        String typeId = params.get("typeId").toString();
        String userId = params.get("userId").toString();
        return new ResultVO(200, "登录成功", taskService.findByUserId(userId));
    }

    public Task convertTask(TaskInfo taskInfo, String userId){
        Task task = new Task();
        task.setTaskId(taskInfo.getId());
        task.setTitle(taskInfo.getTitle());
        task.setContent(taskInfo.getContent());
        task.setJumpUrl(taskInfo.getJumpUrl());
        task.setScore(taskInfo.getScore());
        task.setTypeId(taskInfo.getTypeId());
        task.setIsPress(taskInfo.getIsPress());
        task.setUserId(userId);
        task.setIndustryCode(taskInfo.getIndustryCode());
        task.setLogId(taskInfo.getLogId());
        task.setModifyTime(taskInfo.getModifyTime());
        task.setParams(taskInfo.getParams());
        task.setSubPath(taskInfo.getSubPath());
        return task;
    }
}

二. HttpClient, HttpPost方法:

1。该方法需要在pom.xml中添加httpclient依赖才行:

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

2。公共方法:

package com.example.demo1.test;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import static org.apache.commons.codec.CharEncoding.UTF_8;

public class HttpUtil {

    public static String doPost(JSONObject date) {
        //下面注释掉的语句可以替代第一句
//        HttpClient client = HttpClientBuilder.create().build();
        HttpClient client = HttpClients.createDefault();
        // 要调用的接口方法
        String url = "http://**.**.**.***:1616/api/Task/getList";
        HttpPost post = new HttpPost(url);
        JSONObject jsonObject = null;
        String result = null;
        try {
            System.out.println("params=" +date.toString());
//            StringEntity s = new StringEntity(date.toJSONString(),UTF_8);
            StringEntity s = new StringEntity(date.toString());
//            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            post.setEntity(s);
            post.setHeader("Content-Type", "application/json;charset=UTF-8");
            post.setHeader("accessToken", "********");
            post.setHeader("clientInfo", "{" +
                    "        \"version\": \"6.22.3 \"," +
                    "        \"client\": \"iOS;iPhone XS Max;13.6.0\"" +
                    "      }");
            HttpResponse res = client.execute(post);
            result = EntityUtils.toString(res.getEntity());
            System.out.println(result);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}

3。调用:

在controller中加入:

@RequestMapping("/doPostGetJson")
    @ResponseBody
    public String doPostGetJson() throws ParseException {
        //此处将要发送的数据转换为json格式字符串
        JSONObject json = new JSONObject();
        json.put("typeId", "*****");
        json.put("userId", "*****");
        String sr = HttpUtil.doPost(json);
        System.out.println("返回参数:" + sr);
        return sr;
    }

 

 

 

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值