http远程调用

2019/11/19

通过http访问第三方接口,跳过登录认证(cas)

依赖jar包

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.5</version>
</dependency>
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpmime</artifactId>
  <version>4.5.5</version>
</dependency>

获取会话ID及表单数据方法doCasLoginRequest()

private String[] doCasLoginRequest(HttpClient httpclient, String url) throws IOException {
	try {
		String result[] = new String[5];
		HttpGet httpget = new HttpGet(url);
		HttpResponse response = httpclient.execute(httpget);
		Header[] headers = response.getAllHeaders();
		System.out.println("0000000000000000000000000000000000000000");
		for (int i = 0; i < headers.length; i++) {
			System.out.println(headers[i].getName() + "=" + headers[i].getValue());
		}
		System.out.println("0000000000000000000000000000000000000000");

		// 获取表单数据
		HttpEntity entity = response.getEntity();
		BufferedReader rd = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
		String tempLine = rd.readLine();
		String s = "<input type=\"hidden\" name=\"lt\" value=\"";
		String salt = "<input type=\"hidden\" id=\"pwdDefaultEncryptSalt\" value=\"";
		String x = "<input type=\"hidden\" name=\"execution\" value=\"";
		while (tempLine != null) {
			int index = tempLine.indexOf(s);
			if (index != -1) {
				String s1 = tempLine.substring(index + s.length());
				int index1 = s1.indexOf("\"");
				if (index1 != -1)
					result[0] = s1.substring(0, index1);
			}

			int index_salt = tempLine.indexOf(salt);
			if (index_salt != -1) {
				String s1 = tempLine.substring(index_salt + salt.length());
				int index1 = s1.indexOf("\"");
				if (index1 != -1) {
					result[1] = s1.substring(0, index1);
				}
			}

			int index_x = tempLine.indexOf(x);
			if (index_x != -1) {
				String s1 = tempLine.substring(index_x + x.length());
				int index1 = s1.indexOf("\"");
				if (index1 != -1) {
					result[2] = s1.substring(0, index1);
				}
			}
			tempLine = rd.readLine();
		}

		// 获取会话ID
		Header[] route = response.getHeaders("Set-Cookie");
		if (route != null && route.length > 0) {
			result[3] = route[0].getValue();
			result[4] = route[1].getValue().split("; ")[0];
		} else {
			//
		}

		List<Cookie> cookies = cookieStore.getCookies();
		for (int i = 0; i < cookies.size(); i++) {
			Cookie cookie = cookies.get(i);
			System.err.println(cookie.getDomain() + "\t" + cookie.getName() + "=" + cookie.getValue());
		}

		return result;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}

获取票据方法 getTicketGrantingTicket()

public String getTicketGrantingTicket(final String server, final String username, final String password)
		throws Exception {
	if (this.temp != null) {
		return temp;
	}

	String rs = "";
	HttpPost post = new HttpPost(server);

	List<NameValuePair> nvps = new ArrayList<NameValuePair>();
	String[] temp = doCasLoginRequest(httpclient, server);
	nvps.add(new BasicNameValuePair("username", username));
	nvps.add(new BasicNameValuePair("password", passwordAES(temp[1], password)));
	System.out.println(temp[1] + "+++++++++++++++++++++++++++++++++++++++++++++");
	nvps.add(new BasicNameValuePair("lt", temp[0]));
	nvps.add(new BasicNameValuePair("execution", temp[2]));
	nvps.add(new BasicNameValuePair("_eventId", "submit"));
	nvps.add(new BasicNameValuePair("submit", "登录"));
	nvps.add(new BasicNameValuePair("rmShown", "1"));

	post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
	try {
		HttpResponse response = httpclient.execute(post);
		Header[] headers = response.getAllHeaders();
		for (int i = 0; i < headers.length; i++) {
			System.out.println(headers[i].getName() + "=" + headers[i].getValue());
		}
		System.out.println("========================登录请求返回值=======================");

		// Cookie cookieSessionid = getCookieValue(httpclient, "JSESSIONID");
		Cookie cookieCastgc = getCookieValue("CASTGC");
		rs += cookieCastgc.getValue();
		this.temp = rs;
		return rs;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}

获取图片调用过程 getFile()

public String getFile(HttpServletResponse response, String id) throws Exception {
	try {
		String temp = getTicketGrantingTicket(httpProperties.getJinzhiServer(), httpProperties.getUsername(),
				httpProperties.getPassword());
		System.err.println(temp);
		HttpGet get = new HttpGet(
				"http://ehall.jhun.edu.cn/hqfw/sys/emapcomponent/file/getAttachmentFile/" + id + ".do");

		BasicClientCookie cookie = new BasicClientCookie("CASTGC", temp);
		cookie.setDomain("ehall.jhun.edu.cn");
		cookie.setPath("/");
		cookieStore.addCookie(cookie);
		// post.setHeader("Cookie", temp);

		HttpResponse response1 = httpclient.execute(get);
		System.out.println(response1.getStatusLine().getStatusCode());

		Header[] headers = response1.getAllHeaders();
		String disposition = null;
		for (int i = 0; i < headers.length; i++) {
			String name = headers[i].getName();
			String value = headers[i].getValue();
			System.out.println(name + "=" + value);
			if ("Content-Disposition".equals(name)) {
				disposition = value;
			}
		}

		response.addHeader("Content-Type", "image/*");
		response.addHeader("Content-Disposition", disposition);

		InputStream in = new ByteArrayInputStream(EntityUtils.toByteArray(response1.getEntity()));
		OutputStream out = response.getOutputStream();
		// OutputStream out = new FileOutputStream(new
		// File("C:\\Users\\Administrator\\Desktop\\a.jpg"));
		byte[] buffer = new byte[4096];
		int i = 0;
		while ((i = in.read(buffer)) != -1) {
			out.write(buffer, 0, i);
		}
		out.flush();
		in.close();
		// inputStreamToFile(response1.getEntity().getContent(),
		// "C:\\Users\\chaofan\\Desktop\\my.jpg");
	} catch (Exception e) {
		e.printStackTrace();
	}
	return "SUCCESS";
}

上传图片调用过程 requestUpload()

public String requestUpload(String url, String temp, File file) throws Exception {
	// http://authserver.jhun.edu.cn/authserver/login?service=http://ehall.jhun.edu.cn/hqfw/sys/emapcomponent/file/uploadTempFile.do
	HttpPost post = new HttpPost(url);
	System.err.println(temp);
	BasicClientCookie cookie = new BasicClientCookie("CASTGC", temp);
	cookie.setDomain("ehall.jhun.edu.cn");
	cookie.setPath("/");
	cookieStore.addCookie(cookie);

	if ("http://ehall.jhun.edu.cn/hqfw/sys/emapcomponent/file/uploadTempFile.do".equals(url)) {
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.addBinaryBody("files", file);
		builder.addTextBody("scope", "157414895750982");
		builder.addTextBody("fileToken", "1574148957509821");
		builder.addTextBody("size", "0");
		builder.addTextBody("type", "jpg,jpeg,png");
		builder.addTextBody("storeId", "image");
		builder.addTextBody("isSingle", "0");
		builder.addTextBody("fileName", "");
		post.setEntity(builder.build());
	}
	HttpResponse response1 = httpclient.execute(post);

	StringBuffer sb = new StringBuffer();
	System.out.println(response1.getStatusLine().getStatusCode());
	InputStream is = response1.getEntity().getContent();
	BufferedReader br = new BufferedReader(new InputStreamReader(is));
	String line = "";
	while ((line = br.readLine()) != null) {
		System.out.println("----" + line);
		sb.append(line);
	}

	if (response1.getStatusLine().getStatusCode() == 302) {
		String location = response1.getHeaders("Location")[0].getValue();
		// post.abort();
		return requestUpload(location, temp, file);

	}

	return sb.toString();
}

上传servce

	StringBuffer sb = new StringBuffer();
	MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
	Iterator<String> iter = multiRequest.getFileNames();
	System.out.println();
	while (iter.hasNext()) {
		MultipartFile file = multiRequest.getFile((String) iter.next());
		System.out.println(file.getSize());
		String temp = jinzhiRpc.getTicketGrantingTicket(httpProperties.getJinzhiServer(), httpProperties.getUsername(),
				httpProperties.getPassword());
		File tempFile = new File("F:\\" + file.getOriginalFilename());
		file.transferTo(tempFile);
		sb.append(jinzhiRpc.requestUpload("http://ehall.jhun.edu.cn/hqfw/sys/emapcomponent/file/uploadTempFile.do", temp, tempFile));
	}
	return sb.toString();

Post Directory