将字节流上传到目标地址的工具类
@Component
public class MyHttpClient
{
public void recordInfo(String goalUrl, byte[] bytes) throws Exception
{
long st = System.currentTimeMillis();
String boundary="---*DFSE084*---";
MultipartBody.Builder builder=new MultipartBody.Builder(boundary).setType(MultipartBody.FORM);
builder.addPart(Headers.of("Content-Disposition","form-data; name=\"binary\"; filename=\"qrcode.jpg\""),
RequestBody.create(MediaType.parse("application/octet-stream"), bytes));
RequestBody body=builder.build();
Request req = new Request.Builder().url(goalUrl).post(body).build();
OkHttpClient client=new OkHttpClient();
try(okhttp3.Response resp=client.newCall(req).execute()){
resp.body().string();
long et = System.currentTimeMillis() - st;
com.to8to.rpc.utils.LogUtils.logger().info("将二维码上传到图片服务器,请求耗时:={}",et);
} catch (IOException ex) {
LogUtils.logger().warn("转存失败! 错误信息为:{}", LogUtils.logStackTrace(ex));
}
}
}
代码验证:
public static void main(String[] args) {
String targetPath = "http://pic.xx.com:40009/erp/test.pdf";
Path path = Paths.get("D:\\test.pdf");
try {
byte[] bytes = Files.readAllBytes(path);
recordInfo(targetPath, bytes);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
拨测方法验证:
curl -X PUT -H "Cache-Control: no-cache" -H "Postman-Token: 82f39c8b-1d33-caee-c25b-f6af45431e9d" -H "Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" -F "binary=@[这里是文件路径]" "http://192.168.1.34:40009/qrcode/hmm/feedback_porject.png"