import com.google.gson.Gson;
import com.sun.deploy.net.HttpUtils;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
;
/**
* Created by atuhor on 2021-05-27.
*/
public class main {
public static void main(String[] args) {
String fileName="D:\\pic\\202105082140017318.jpg";
upLoadImg(fileName);
System.out.println("hello world");
}
public static String doPostJson(String url, String json) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建请求内容
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return resultString;
}
/**
* 外网api获取ossToken
*/
public static Map getOSSToken(String name){
String code = "t_js_jsceshi";
// 捷顺接口HTTP账户
/* if(new StrUtil().Stil(U.getGlobalStrategy(NonstandardUtil.PARAM_10, null))){
code = U.getGlobalStrategy(NonstandardUtil.PARAM_10, null);
}else{
return null;
}*/
Map map = new HashMap();
Map result = new HashMap();
map.put("user", "Y3AtRUNJUC1DUE1QLUNPU99kU6");
map.put("key", "fab67b38a582191f2");
map.put("container", "cpt");
map.put("ossObject","333433");// code+"/P_IMG_PARK_IN/"+new SimpleDateFormat("yyyyMMdd").format(new Date())+"/"+name);
Gson gson = new Gson();
String json = gson.toJson(map);
new HttpUtils();
String postJson = doPostJson("http://127.0.0.1:8081/shunfeng/oss/getV2Token",json);
Map fromJson = gson.fromJson(postJson, Map.class);
if(fromJson!=null &&((Double)fromJson.get("status")).intValue()==200){
Map respData = (Map)fromJson.get("respData");
String replaceFirst = respData.get("storageUrl").toString().replaceFirst("v1", "v1.2");
result.put("storageUrl", replaceFirst);
result.put("token", respData.get("token").toString());
System.out.println("oss图片名称:"+name);
System.out.println("oss请求地址:"+replaceFirst);
System.out.println("ossToken:"+respData.get("token").toString());
}else{
return null;
}
return result;
}
/**
* http put请求 文件上传字节流
* @param path
* @param obj
* @throws IOException
* @throws JSONException
*/
public static void getUploadInformation(String path,String token,File file) throws IOException, JSONException {
//创建连接
URL url = new URL(path);
HttpURLConnection connection ;
BufferedInputStream buf=null;
try {
//添加 请求内容
connection= (HttpURLConnection) url.openConnection();
//设置http连接属性
connection.setDoOutput(true);// http正文内,因此需要设为true, 默认情况下是false;
connection.setDoInput(true);// 设置是否从httpUrlConnection读入,默认情况下是true;
connection.setRequestMethod("PUT"); // 可以根据需要 提交 GET、POST、DELETE、PUT等http提供的功能
connection.setRequestProperty("Content-Type", "multipart/form-data");//设定 请求格式 json,也可以设定xml格式的
connection.setRequestProperty("Accept-Charset", "utf-8"); //设置编码语言
connection.setRequestProperty("X-Auth-Token", token); //设置请求的token
connection.setRequestProperty("Connection", "keep-alive"); //设置连接的状态
connection.setRequestProperty("Transfer-Encoding", "chunked");//设置传输编码
connection.setReadTimeout(10000);//设置读取超时时间
connection.setConnectTimeout(10000);//设置连接超时时间
connection.connect();
OutputStream out = connection.getOutputStream();//向对象输出流写出数据,这些数据将存到内存缓冲区中
buf=new BufferedInputStream(new FileInputStream(file));
byte[] buffer=new byte[1024];
while(buf.read(buffer)!=-1) {
out.write(buffer);
}
//写出到请求的地方
out.flush();
// 关闭流对象,此时,不能再向对象输出流写入任何数据,先前写入的数据存在于内存缓冲区中
out.close();
//读取响应
if (connection.getResponseCode()==201){
// 从服务器获得一个输入流
System.out.println("顺丰OSS系统上传图片对象成功!");
}else{
System.out.println("请求失败"+connection.getResponseCode());
}
//断开连接
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
//上传图片值oss系统
private static void upLoadImg(String fileName){
File file = new File(fileName);
// LoginImpl loginImpl = new LoginImpl();
String name = file.getName();
Map ossToken = getOSSToken(name);
String token = ossToken.get("token").toString();
String storageUrl = ossToken.get("storageUrl").toString();
HttpUtils httpUtils = new HttpUtils();
try {
getUploadInformation(storageUrl,token,file);
} catch (IOException e) {
e.printStackTrace();
}
}
}