上传指定位置文件到指定url服务器

static String boundary = “abcde12345”;
static String prefix = “–”;
static String newLine = “\r\n”;

public static void test(String serverUrl,String path) {
    try {
        URL url = new URL(serverUrl);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-type", "multipart/form-data;boundary=" + boundary);
        ConfigHttpMultipart(connection.getOutputStream(),path);
        InputStream ins = connection.getInputStream();
        byte[] b = readBuffer(ins);
        System.out.println(new String(b));
    } catch (MalformedURLException e) {
        System.out.println(" url error! ");
    } catch (IOException e) {
        System.out.println(" io error! ");
    }
}

private static void ConfigHttpMultipart(final OutputStream out,String filepath) {
    StringBuffer params = new StringBuffer();

// params.append(prefix + boundary + newLine);
// params.append(“Content-Disposition: form-data; name=“jsonData””);
// params.append(newLine + newLine);
// String jsonData = “{“test”:“test message!”}”;
// params.append(jsonData);
// params.append(newLine);
params.append(prefix + boundary + newLine);
String name=filepath.substring(filepath.lastIndexOf("/")+1,filepath.length());
Log.i(TAG,“name :”+name);
params.append(“Content-Disposition: form-data; name=“file”; filename=”").append(name).append(""");
params.append(newLine);
params.append(“Content-Type: multipart/form-data”);
params.append(newLine + newLine);
File file = new File(filepath);
Log.i(TAG, file.isFile()+", “+ file.exists()+”, “+ file.length()+“filepath :”+filepath);
try {
InputStream in = new FileInputStream(file);
out.write(params.toString().getBytes());
out.write(readBuffer(in));
out.write(newLine.getBytes());
out.write((prefix + boundary + prefix + newLine).getBytes());
out.flush();
out.close();
} catch (FileNotFoundException e) {
System.out.println(” no file! “);
} catch (IOException e) {
System.out.println(” io error! ");
}
}

public static byte[] readBuffer(final InputStream ins) throws IOException {
    byte b[] = new byte[1024];
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    int len = 0;
    while ((len = ins.read(b)) != -1) {
        stream.write(b, 0, len);
    }
    Log.i(TAG,stream.size()+"");
    return stream.toByteArray();
}

2.https://blog.csdn.net/u014026084/article/details/73124157

3.https://www.cnblogs.com/lipeineng/p/5731604.html

以上三种方法第一种方法,亲测可用,直接调用过去即可

你可能感兴趣的:(上传指定位置文件到指定url服务器)