图片流及cookie获取
This commit is contained in:
49
src/main/java/com/tem/bocai/util/ImageTest.java
Normal file
49
src/main/java/com/tem/bocai/util/ImageTest.java
Normal file
@@ -0,0 +1,49 @@
|
||||
package com.tem.bocai.util;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class ImageTest {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
getImageStreamAndCookie("https://4701268539-esh.qdk63ayw8g.com/code?_=1768901529986");
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据URL获取图片流及cookie
|
||||
* @param imageUrl 图片URL
|
||||
* @return Object[] 返回数组,索引0为图片InputStream,索引1为cookie字符串
|
||||
* @throws Exception 抛出异常
|
||||
*/
|
||||
public static Object[] getImageStreamAndCookie(String imageUrl) throws Exception {
|
||||
URL url = new URL(imageUrl);
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setRequestMethod("GET");
|
||||
connection.setConnectTimeout(5000);
|
||||
connection.setReadTimeout(5000);
|
||||
|
||||
// 获取图片流
|
||||
InputStream imageStream = connection.getInputStream();
|
||||
|
||||
// 获取cookie
|
||||
StringBuilder cookieBuilder = new StringBuilder();
|
||||
Map<String, List<String>> headerFields = connection.getHeaderFields();
|
||||
List<String> cookies = headerFields.get("Set-Cookie");
|
||||
if (cookies != null) {
|
||||
for (String cookie : cookies) {
|
||||
// 只取cookie的name=value部分,忽略其他属性
|
||||
String cookieValue = cookie.split(";\s*")[0];
|
||||
cookieBuilder.append(cookieValue).append("; ");
|
||||
}
|
||||
// 移除最后一个分号和空格
|
||||
if (cookieBuilder.length() > 0) {
|
||||
cookieBuilder.setLength(cookieBuilder.length() - 2);
|
||||
}
|
||||
}
|
||||
|
||||
return new Object[]{imageStream, cookieBuilder.toString()};
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user