package com.mw.guahu.util;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;


import android.util.Log;


public class Https {
final String ENCORDING="UTF-8";
public boolean upload(String filepath) throws Exception {
String boundary = UUID.randomUUID().toString();//+java.util.UUID.randomUUID().toString();//
// 分割线
File file = new File(filepath);

// String fileName=new String("哈哈嗨".getBytes(),"ISO-8859-1");
// 用来解析主机名和端口
URL url = new URL("http://192.168.0.119:8080/MojieProject/artic/addArtic.do");
// 用来开启连接
StringBuilder sb = new StringBuilder();
// 用来拼装请求


// 文件部分
sb.append("--" + boundary + "\r\n");
sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + filepath + "\"" + "\r\n");
sb.append("Content-Type: application/octet-stream" + "\r\n");
sb.append("\r\n");

// 将开头和结尾部分转为字节数组,因为设置Content-Type时长度是字节长度
byte[] before = sb.toString().getBytes(ENCORDING);
byte[] after = ("\r\n--" + boundary + "--\r\n").getBytes(ENCORDING);

// 打开连接, 设置请求头
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
conn.setRequestProperty("Content-Length", before.length + file.length() + after.length + "");

conn.setDoOutput(true);
conn.setDoInput(true);

// 获取输入输出流
OutputStream out = conn.getOutputStream();
FileInputStream fis = new FileInputStream(file);
// 将开头部分写出
out.write(before);

// 写出文件数据
byte[] buf = new byte[1024*5];
int len;
while ((len = fis.read(buf)) != -1)
out.write(buf, 0, len);

// 将结尾部分写出
out.write(after);

InputStream in = conn.getInputStream();
InputStreamReader isReader = new InputStreamReader(in);
BufferedReader bufReader = new BufferedReader(isReader);
String line = null;
String data = "getResult=";
while ((line = bufReader.readLine()) != null)
data += line;
Log.d("fromServer", "result="+data);
boolean sucess=conn.getResponseCode() == 200;
in.close();
fis.close();
out.close();
conn.disconnect();

return sucess;
}
}

更多相关文章

  1. 字节跳动大牛最佳整理:582页Android(安卓)NDK七大模块学习宝典,理
  2. 2020年最新阿里、字节、腾讯、京东等一线大厂高频面试(Android岗)
  3. Android中,Dalvik检查和优化.apk/.jar的流程introduce
  4. 00003 不思议迷宫.0011.2:Android新版中的Lua加密(下)
  5. 腾讯、网易云、字节跳动面试点总结—AMS在Android起到什么作用?
  6. Android(安卓)文件IO操作
  7. Android(安卓)如何正确使用我们的图片资源
  8. 利用WCF与Android实现图片上传并传参
  9. android学习笔记之图像像素操作

随机推荐

  1. LinearLayout和RelativeLayout的比较
  2. Android 4编程入门经典—开发智能手机与
  3. Android编译过程详解
  4. [Android 新特性] 改进明显 Android 4.4
  5. Activity属性设置大全
  6. Android GridView 使用示例
  7. 从零开始--系统深入学习android(实践-让我
  8. android检测当前网络是否可用
  9. Android笔记_Linearlayout(线性布局)
  10. Android全屏显示的两种方式