package com.sh.yyzzqz.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 用于模拟HTTP请求中GET/POST方式
*
* @author landa
*/
public class HttpUtilS {
/**
* 发送GET请求
*
* @param url 目的地址
* @param parameters 请求参数,Map类型。带有请求头
* @return 远程响应结果
*/
public static String sendGet(String url, Map<String, String> parameters, String Authorization) {
String result = "";
BufferedReader in = null;// 读取响应输入流
StringBuffer sb = new StringBuffer();// 存储参数
String params = "";// 编码之后的参数
try {
// 编码请求参数
if (parameters.size() == 1) {
for (String name : parameters.keySet()) {
sb.append(name).append("=").append(
URLEncoder.encode(parameters.get(name),
"UTF-8"));
}
params = sb.toString();
} else {
for (String name : parameters.keySet()) {
sb.append(name).append("=").append(
URLEncoder.encode(parameters.get(name),
"UTF-8")).append("&");
}
String temp_params = sb.toString();
params = temp_params.substring(0, temp_params.length() - 1);
}
String full_url = url + "?" + params;
System.out.println(full_url);
// 创建URL对象
URL connURL = new URL(full_url);
// 打开URL连接
HttpURLConnection httpConn = (HttpURLConnection) connURL
.openConnection();
// 设置通用属性
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Connection", "Keep-Alive");
//httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36)");
//设置带有请求头
httpConn.setRequestProperty("Authorization", Authorization);
// 建立实际的连接
httpConn.connect();
// 响应头部获取
Map<String, List<String>> headers = httpConn.getHeaderFields();
// 遍历所有的响应头字段
for (String key : headers.keySet()) {
System.out.println(key + "\t:\t" + headers.get(key));
}
// 定义BufferedReader输入流来读取URL的响应,并设置编码方式
in = new BufferedReader(new InputStreamReader(httpConn
.getInputStream(), "UTF-8"));
String line;
// 读取返回的内容
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* 发送POST请求
*
* @param url 目的地址
* @param parameters 请求参数,Map类型。 发送的是formdata参数以key=value的形式 带有请求头
* @return 远程响应结果
*/
public static String sendPostKY(String url, Map<String, Object> parameters, String Authorization) {
String result = "";// 返回的结果
BufferedReader in = null;// 读取响应输入流
PrintWriter out = null;
StringBuffer sb = new StringBuffer();// 处理请求参数
String params = "";// 编码之后的参数
try {
// 编码请求参数
if (parameters.size() == 1) {
for (String name : parameters.keySet()) {
sb.append(name).append("=").append(
URLEncoder.encode(parameters.get(name).toString(),
"UTF-8"));
}
params = sb.toString();
} else {
for (String name : parameters.keySet()) {
sb.append(name).append("=").append(
URLEncoder.encode(parameters.get(name).toString(),
"UTF-8")).append("&");
}
String temp_params = sb.toString();
params = temp_params.substring(0, temp_params.length() - 1);
}
// System.out.println("URL参数---"+params);
// 创建URL对象
URL connURL = new URL(url);
// 打开URL连接
HttpURLConnection httpConn = (HttpURLConnection) connURL
.openConnection();
// 设置通用属性
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Connection", "Keep-Alive");
//在这里加上请求头授权
httpConn.setRequestProperty("Authorization", Authorization);
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
// 设置POST方式
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
// 获取HttpURLConnection对象对应的输出流
out = new PrintWriter(httpConn.getOutputStream());
// 发送请求参数
out.write(params);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应,设置编码方式
in = new BufferedReader(new InputStreamReader(httpConn
.getInputStream(), "UTF-8"));
String line;
// 读取返回的内容
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* 发送POST请求
*
* @param url 目的地址
* @param 请求参数,Map类型。 发送的是json的格式 带有Header请求头
* @return 远程响应结果
*/
public static String doPost(Map<String, Object> param, String url, String Authorization) throws Exception {
HttpClient httpclient = HttpClientBuilder.create().build();
HttpPost http = new HttpPost(url);
String jsonParam = JSON.toJSONString(param, SerializerFeature.WriteMapNullValue);
HttpEntity body = new StringEntity(jsonParam, "UTF-8");
http.setEntity(body);
http.setHeader("Content-type", "application/json;charset=utf-8");
//在这里加上请求头信息
http.setHeader("Authorization", Authorization);
HttpResponse response = null;
response = httpclient.execute(http);
HttpEntity entity = response.getEntity();
String context = "";
if (entity != null) {
//getResponse
InputStream in = entity.getContent();
byte[] data = transformInputstream(in);
context = new String(data, "UTF-8");
}
return context;
}
/**
* 发送POST请求 返回数据直接是文件流
*
* @param url 目的地址
* @param 请求参数,Map类型。 发送的是formdata参数以key=value的形式 带有请求头
* @return 远程响应结果
*/
public static String sendPostKYOne(String url, Map<String, Object> parameters, String Authorization) {
String result = "";// 返回的结果
BufferedReader in = null;// 读取响应输入流
PrintWriter out = null;
StringBuffer sb = new StringBuffer();// 处理请求参数
String params = "";// 编码之后的参数
try {
// 编码请求参数
if (parameters.size() == 1) {
for (String name : parameters.keySet()) {
sb.append(name).append("=").append(
java.net.URLEncoder.encode(parameters.get(name).toString(),
"UTF-8"));
}
params = sb.toString();
} else {
for (String name : parameters.keySet()) {
sb.append(name).append("=").append(
java.net.URLEncoder.encode(parameters.get(name).toString(),
"UTF-8")).append("&");
}
String temp_params = sb.toString();
params = temp_params.substring(0, temp_params.length() - 1);
}
// System.out.println("URL参数---"+params);
// 创建URL对象
URL connURL = new URL(url);
// 打开URL连接
HttpURLConnection httpConn = (HttpURLConnection) connURL
.openConnection();
// 设置通用属性
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Connection", "Keep-Alive");
//设置请求头部信息
httpConn.setRequestProperty("Authorization", Authorization);
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConn.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
// 设置POST方式
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
// 获取HttpURLConnection对象对应的输出流
out = new PrintWriter(httpConn.getOutputStream());
// 发送请求参数
out.write(params);
// flush输出流的缓冲
out.flush();
//这里把文件流转为base64返回
InputStream inputStream = httpConn.getInputStream();
String s = inputStream2Base64(inputStream);
return s;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* 发送POST请求 带有文件以及其他参数 文件类型为MultipartFile
*
* @param url 目的地址
* @param 请求参数,Map类型。 发送的是formdata参数以key=value的形式 带有请求头
* @return 远程响应结果
*/
public static String doPost(String url, MultipartFile multipartFile, String fileParName, Map<String, Object> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//文件传输参数名 file
builder.addBinaryBody("file", multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, multipartFile.getOriginalFilename());// 文件流
//决中文乱码
ContentType contentType = ContentType.create("application/x-www-form-urlencoded", HTTP.UTF_8);
for (Map.Entry<String, Object> entry : params.entrySet()) {
if(entry.getValue() == null)
continue;
// 类似浏览器表单提交,对应input的name和value
builder.addTextBody(entry.getKey(), entry.getValue().toString(),contentType);
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
private static byte[] transformInputstream(InputStream input) throws Exception {
byte[] byt = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int b = 0;
b = input.read();
while (b != -1) {
baos.write(b);
b = input.read();
}
byt = baos.toByteArray();
return byt;
}
private static String inputStream2Base64(InputStream is) throws Exception {
byte[] data = null;
try {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = is.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
data = swapStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
throw new Exception("输入流关闭异常");
}
}
}
return Base64.getEncoder().encodeToString(data);
}
/**
* @return java.io.File
* @author yyh
* @Description: base64转换为文件
* @date 2022-11-18 16:42
* @Param [base64(图片数据), filePath(文件绝对路径,如果此参数不为空在硬盘中创建文件后面参数不起作用,否则创建临时文件),
* fileName(文件名称), suffix(文件后缀)]
*/
public static File base64ToFile(String base64, String filePath, String fileName, String suffix) throws IOException {
/* if(base64.contains("data:image")){
base64 = base64.substring(base64.indexOf(",")+1);
}*/
base64 = base64.replace("\r\n", "").replace(" ", "");
if (base64.contains(",")) {
base64 = base64.split(",")[1];
}
//创建文件目录
File file = null;
//有路径时保存到硬盘目录没有时创建临时文件
if (org.springframework.util.StringUtils.hasLength(filePath)) {
file = new File(filePath);
File parentFile = file.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
} else {
file = File.createTempFile(fileName, suffix);
}
BufferedOutputStream bos = null;
FileOutputStream fos = null;
try {
// BASE64Decoder decoder = new BASE64Decoder();
// byte[] bytes = decoder.decodeBuffer(base64);
//byte[] bytes = Base64.getDecoder().decode(base64);
byte[] bytes = org.apache.tomcat.util.codec.binary.Base64.decodeBase64(base64);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return file;
}
/**
* @return java.lang.String
* @author yyh
* @Description: 根据文件路径转换为base64
* @date 2022-11-18 17:46
* @Param [path]
*/
public static String fileToBase64(String path) throws FileNotFoundException {
String base64 = null;
InputStream in = null;
try {
File file = new File(path);
base64 = fileToBase64(file);
//base64 = Base64.getEncoder().encodeToString(bytes);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return base64;
}
/**
* @param file File转换为base64
* @return
* @throws IOException
*/
public static String fileToBase64(File file) throws IOException {
String base64 = null;
InputStream in = null;
try {
in = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
in.read(bytes);
base64 = org.apache.tomcat.util.codec.binary.Base64.encodeBase64String(bytes);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return base64;
}
/**
* @param filePaths 需要压缩的文件地址列表(绝对路径)
* @param zipFilePath 需要压缩到哪个zip文件(无需创建这样一个zip,只需要指定一个全路径)
* @param keepDirStructure 压缩后目录是否保持原目录结构
* @return int 压缩成功的文件个数
* @throws IOException
* @Title: compress
* @Description: 多个文件压缩为zip格式
*/
public static int compress(List<String> filePaths, String zipFilePath, Boolean keepDirStructure) throws IOException {
byte[] buf = new byte[1024];
File zipFile = new File(zipFilePath);
//zip文件不存在,则创建文件,用于压缩
if (!zipFile.exists())
zipFile.createNewFile();
int fileCount = 0;//记录压缩了几个文件?
try {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
for (int i = 0; i < filePaths.size(); i++) {
String relativePath = filePaths.get(i);
if (!StringUtils.hasLength(relativePath)) {
continue;
}
File sourceFile = new File(relativePath);//绝对路径找到file
if (sourceFile == null || !sourceFile.exists()) {
continue;
}
FileInputStream fis = new FileInputStream(sourceFile);
if (keepDirStructure != null && keepDirStructure) {
//保持目录结构
zos.putNextEntry(new ZipEntry(relativePath));
} else {
//直接放到压缩包的根目录
zos.putNextEntry(new ZipEntry(sourceFile.getName()));
}
//System.out.println("压缩当前文件:"+sourceFile.getName());
int len;
while ((len = fis.read(buf)) > 0) {
zos.write(buf, 0, len);
}
zos.closeEntry();
fis.close();
fileCount++;
}
zos.close();
System.out.println("压缩完成");
} catch (Exception e) {
e.printStackTrace();
}
return fileCount;
}
/**
* 根据文件url获取文件并转换为base64编码
*
* @param srcUrl 文件地址
* @param requestMethod 请求方式("GET","POST")
* @return 文件base64编码
*/
public static String netSourceToBase64(String srcUrl, String requestMethod) {
ByteArrayOutputStream outPut = new ByteArrayOutputStream();
byte[] data = new byte[1024 * 8];
try {
// 创建URL
URL url = new URL(srcUrl);
// 创建链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(requestMethod);
conn.setConnectTimeout(100 * 1000);
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
//连接失败/链接失效/文件不存在
return null;
}
InputStream inStream = conn.getInputStream();
int len = -1;
while (-1 != (len = inStream.read(data))) {
outPut.write(data, 0, len);
}
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(outPut.toByteArray());
}
/**
* 主函数,测试请求
*
* @param args
*/
public static void main(String[] args) {
/* Map<String, String> parameters = new HashMap<String, String>();
parameters.put("name", "sarin");
String result =sendGet("http://www.baidu.com", parameters);
System.out.println(result);*/
String url = "http://59.207.153.24:8040/license-api-release/m/v/license/image_base64_by_qrycode?qryCode=WHBic1ZLbnBRcjFJRng3RFhZZ2Z4cm1OczZXdFViaWpNRWhHZVVsalArVWhNUk9PSU1QZFpDaXBFUzhNTVBUTQ==";
String path = "D:/downloadFile";
//downloadPicture(url,path);
}
}
java发送http各种请求以及文件转换
于 2023-07-28 11:17:41 首次发布