okhttp远程调用

2019/11/20

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

依赖jar包

<dependency>
	<groupId>com.squareup.okhttp3</groupId>
	<artifactId>okhttp</artifactId>
	<version>3.8.0</version>
</dependency>

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

public static String[] doCasLoginRequest() throws IOException {
	String result[] = new String[5];
	Response response = okHttpClient.newCall(get(server)).execute();

	BufferedReader rd = new BufferedReader(new InputStreamReader(response.body().byteStream(), "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) {
		System.out.println(tempLine);
		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();
	}

	List<String> route = response.headers("Set-Cookie");
	for (String string : route) {
		System.out.println("------------------------------------------------------");
		System.err.println(string);
		System.out.println("------------------------------------------------------");
	}
	if (route != null && route.size() > 0) {
		result[3] = route.get(0);
		result[4] = route.get(1).split("; ")[0];
	} else {
		//
	}

	return result;
}

获取票据方法 getTicketGrantingTicket()

public static void getTicketGrantingTicket() throws IOException { List data = MyCookieJar.cookieStore.get("jhun.edu.cn"); if (data != null && data.size() > 0) { return; }

	String[] temp = doCasLoginRequest();
	Map<String, Object> form = new HashMap<String, Object>();
	form.put("lt", temp[0]);
	form.put("username", username);
	form.put("password", passwordAES(temp[1]));
	form.put("dllt", "userNamePasswordLogin");
	form.put("execution", "e1s1");
	form.put("_eventId", "submit");
	form.put("rmShown", "1");

	String str = getUrlParamsByMap(form);
	System.out.println("参数:" + str);
	RequestBody body = RequestBody.create(FORM, str);

	String cookie = temp[3] + "; org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=zh_CN; "
			+ temp[4];
	System.out.println("cookie参数值:" + cookie);
	Request request = new Request.Builder().url("http://authserver.jhun.edu.cn/authserver/login")
			.addHeader("Cookie", cookie).addHeader("Referer", "http://authserver.jhun.edu.cn/authserver/login")
			.addHeader("Origin", "http://authserver.jhun.edu.cn")
			.addHeader("Accept",
					"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3")
			.addHeader("Accept-Encoding", "gzip, deflate").addHeader("Accept-Language", "zh-CN,zh;q=0.9")
			.addHeader("Cache-Control", "max-age=0").addHeader("Connection", "keep-alive")
			.addHeader("Host", "authserver.jhun.edu.cn")
			.addHeader("User-Agent",
					"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36")
			.addHeader("Upgrade-Insecure-Requests", "1").post(body).build();
	Response response = okHttpClient.newCall(request).execute();
	System.err.println("==============登录返回值=================");
	System.out.println("response状态码:" + response.code());
	System.out.println("response结果:" + response.body().string());
	return;
}

获取图片调用过程 getFile()

public static void getFile(String id, HttpServletResponse response) {
	try {
		getTicketGrantingTicket();
		doGet(response, "http://ehall.jhun.edu.cn/hqfw/sys/emapcomponent/file/getAttachmentFile/" + id + ".do");
	} catch (Exception e) {
		e.printStackTrace();
	}
}

private static void doGet(HttpServletResponse response, String url) throws IOException {
	Request request = new Request.Builder().get().url(url).build();

	Response res = okHttpClient.newCall(request).execute();

	if (res.code() == 302) {
		System.err.println("==============转发=================");
		System.out.println("response状态码:" + res.code());
		System.out.println("response结果:" + res.body().string());

		String location = res.header("Location");
		doGet(response, location);
	} else {
		String disposition = res.header("Content-Disposition");
		response.addHeader("Content-Type", "image/*");
		response.addHeader("Content-Disposition", disposition);

		InputStream in = res.body().byteStream();
		OutputStream out = response.getOutputStream();
		// OutputStream out = new FileOutputStream(new
		// File("C:\\Users\\Administrator\\Desktop\\a.png"));
		byte[] buffer = new byte[4096];
		int i = 0;
		while ((i = in.read(buffer)) != -1) {
			out.write(buffer, 0, i);
		}
		out.flush();
		in.close();
	}
}

上传图片调用过程 requestUpload()

public static String upload(String url, File file) {
	try {
		getTicketGrantingTicket();

		okhttp3.Request.Builder build = new Request.Builder();
		if ("http://ehall.jhun.edu.cn/hqfw/sys/emapcomponent/file/uploadTempFile.do".equals(url)) {
			// form 表单形式上传
			MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
			if (file != null) {
				// MediaType.parse() 里面是上传的文件类型。
				RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), file);
				String filename = file.getName();
				// 参数分别为, 请求key(随机字符用于前后包夹流) ,文件名称 , RequestBody
				requestBody.addFormDataPart("files", filename, body);
			}
			requestBody.addFormDataPart("scope", "155503687442745");
			requestBody.addFormDataPart("fileToken", "1555036874427451");
			requestBody.addFormDataPart("size", "0");
			requestBody.addFormDataPart("type", "jpg,jpeg,png");
			requestBody.addFormDataPart("storeId", "image");
			requestBody.addFormDataPart("isSingle", "0");
			requestBody.addFormDataPart("fileName", "");

			build.post(requestBody.build());
		} else {
			build.post(new FormBody.Builder().build());
		}

		Request request = build.url(url).build();
		Response response = okHttpClient.newCall(request).execute();
		System.err.println("=======================请求返回值========================");
		System.out.println(response.body().string());
		if (response.code() == 302) {
			String location = response.header("Location");
			// post.abort();
			return upload(location, file);

		}

		return response.body().string();
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}

上传servce

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

Post Directory