java实现 一个项目使用http请求远程调用其他项目,传参,携带cookie实现远程传参调用

2022-08-16 08:17:49 浏览数 (1)

这里写目录标题

  • 1 远程获取cookie
  • 2 远程调用其他项目(传参,携带cookie)

1 远程获取cookie

参数 url 是远程项目的地址。map集合是参数

代码语言:javascript复制
    /**
     * @Description:   登录成功获取cookie
     */
       public static Map<String, Object> postForForm(String url, Map<String, String> parms) {

        HttpPost httpPost = new HttpPost(url);
        ArrayList<BasicNameValuePair> list = new ArrayList<>();
        parms.forEach((key, value) -> list.add(new BasicNameValuePair(key, value)));
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            if (Objects.nonNull(parms) && parms.size() >0) {
                httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
            }
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            InputStream content = httpPost.getEntity().getContent();
            InputStreamReader inputStreamReader = new InputStreamReader(content, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String readLine = bufferedReader.readLine();
            String s = URLDecoder.decode(readLine, "UTF-8");
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            Header[] allHeaders = response.getAllHeaders();
            // 遍历以获取名为"Set-Cookie"的响应头,并赋值给变量cookie
            String cookie = "";
            for (Header header : allHeaders) {
                if ("Set-Cookie".contentEquals(header.getName())) {
                    cookie = header.getValue();
                }
            }
//            System.out.println(cookie);
            String result= EntityUtils.toString(entity, "UTF-8");
            Map<String, Object> stringObjectHashMap = new HashMap<>();
            stringObjectHashMap.put("cookie",cookie);
            stringObjectHashMap.put("result",result);
            return stringObjectHashMap;
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (Objects.nonNull(httpClient)){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

controller层

代码语言:javascript复制
 public void getXxlJobToken( ) {
        Map<String, String> sendMsg = new HashMap<String, String>();
        sendMsg.put("userName", userName);
        sendMsg.put("password", password);
        sendMsg.put("ifRemember", ifRemember);

        Map<String, Object> stringObjectMap = HttpSSLUtil.postForForm(webLoginUrl, sendMsg);
        Cookieinfo = (String) stringObjectMap.get("cookie");
//        System.out.println(Cookieinfo);

    }

远程地址 接收参数代码

代码语言:javascript复制
	@RequestMapping(value="login", method=RequestMethod.POST)
	@ResponseBody
	@PermissionLimit(limit=false)
	public ReturnT<String> loginDo(HttpServletRequest request, HttpServletResponse response, String userName, String password, String ifRemember){
		boolean ifRem = (ifRemember!=null && ifRemember.trim().length()>0 && "on".equals(ifRemember))?true:false;
		return loginService.login(request, response, userName, password, ifRem);
	}

2 远程调用其他项目(传参,携带cookie)

工具类方法

代码语言:javascript复制
    /**
     * @Description:   携带cookie进行调用
     */
    public static String postForFormCookie(String url111, String parms,String cookies) {

        OutputStreamWriter out = null ;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
//        String url111 = "http://192.168.1.5:8080/xxl-job-admin/jobinfo/updatedemo";

        try {
            URL realUrl = new URL(url111);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
            //设置通用的请求头属性
//            conn.setRequestMethod("POST");
            conn.setRequestProperty("Cookie", cookies);
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行   否则会抛异常(java.net.ProtocolException: cannot write to a URLConnection if doOutput=false - call setDoOutput(true))
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //获取URLConnection对象对应的输出流并开始发送参数
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            //添加参数
//            DataOutputStream output = null;
//            output =  new DataOutputStream(conn.getOutputStream());
            out.write(parms);
//            output.writeBytes(xxlJobInfo1.toString());
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {// 使用finally块来关闭输出流、输入流
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
//        System.out.println(result.toString());


}

使用

代码语言:javascript复制
    String updatepath= addressInfo "/jobinfo/update";
//        System.out.println(updatepath);
        String param = "&id=" id "&jobGroup=";
        String s = HttpSSLUtil.postForFormCookie(updatepath,param, XxlJobController.Cookieinfo);

远程项目可以使用实体类进行接收

代码语言:javascript复制
	/**
	 * 更新任务
	 */
	@RequestMapping("/update")
	@ResponseBody
	public ReturnT<String> update(XxlJobInfo jobInfo) {
		return xxlJobService.update(jobInfo);
	}

0 人点赞