Http socket Upload - Android Network

Android examples for Network:HTTP

Description

Http socket Upload

Demo Code


//package com.java2s;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStreamReader;
import java.io.OutputStream;

import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;

import java.util.HashMap;
import java.util.Map;

public class Main {
    private static Map<String, String> cookieCache = new HashMap<String, String>();

    public static boolean socketUpload(String uploadUrl,
            Map<String, String> params, String fieldName, File... files)
            throws IOException {
        final String BOUNDARY = "---------------------------"; //?
        final String endLine = "--" + BOUNDARY + "--\r\n";//
        int fileDataLength = 0;
        for (File uploadFile : files) {//
            StringBuilder fileBody = new StringBuilder();
            fileBody.append("--");
            fileBody.append(BOUNDARY);//from  w ww .ja  v  a  2  s.c  o m
            fileBody.append("\r\n");
            fileBody.append("Content-Disposition: form-data;name=\""
                    + fieldName + "\";filename=\"" + uploadFile.getName()
                    + "\"\r\n");
            fileBody.append("Content-Type: application/octet-stream\r\n\r\n");
            fileBody.append("\r\n");
            fileDataLength += fileBody.length();
            fileDataLength += uploadFile.length();
        }
        StringBuilder textBody = new StringBuilder();
        if (params != null && params.size() > 0) {
            for (Map.Entry<String, String> entry : params.entrySet()) {//?
                textBody.append("--");
                textBody.append(BOUNDARY);
                textBody.append("\r\n");
                textBody.append("Content-Disposition: form-data; name=\""
                        + entry.getKey() + "\"\r\n\r\n");
                textBody.append(entry.getValue());
                textBody.append("\r\n");
            }
        }
        //?
        int dataLength = textBody.toString().getBytes().length
                + fileDataLength + endLine.getBytes().length;
        URL url = new URL(uploadUrl);
        String host = url.getHost();
        int port = url.getPort() == -1 ? 80 : url.getPort();
        Socket socket = new Socket(InetAddress.getByName(url.getHost()),
                port);
        OutputStream outStream = socket.getOutputStream();
        //?HTTP?
        String method = "POST " + url.getPath() + " HTTP/1.1\r\n";
        outStream.write(method.getBytes());
        String accept = "Accept: */*\r\n";
        outStream.write(accept.getBytes());
        outStream.write("Accept-Charset: UTF-8\r\n".getBytes());
        String language = "Accept-Language: zh-CN\r\n";
        outStream.write(language.getBytes());
        String cookie = cookieCache.get(host);
        if (cookie != null) {
            cookie = "Cookie: " + cookie + "\r\n";
            outStream.write(cookie.getBytes());
        }
        String contentType = "Content-Type: multipart/form-data; boundary="
                + BOUNDARY + "\r\n";
        outStream.write(contentType.getBytes());
        String contentLength = "Content-Length: " + dataLength + "\r\n";
        outStream.write(contentLength.getBytes());
        String alive = "Connection: Keep-Alive\r\n";
        outStream.write(alive.getBytes());
        host = "Host: " + url.getHost() + ":" + port + "\r\n";
        outStream.write(host.getBytes());
        //HTTPHTTP?
        outStream.write("\r\n".getBytes());
        //?
        outStream.write(textBody.toString().getBytes());
        //?
        for (File uploadFile : files) {
            StringBuilder fileBody = new StringBuilder();
            fileBody.append("--");
            fileBody.append(BOUNDARY);
            fileBody.append("\r\n");
            fileBody.append("Content-Disposition: form-data;name=\""
                    + fieldName + "\";filename=\"" + uploadFile.getName()
                    + "\"\r\n");
            fileBody.append("Content-Type: application/octet-stream\r\n\r\n");
            outStream.write(fileBody.toString().getBytes());
            byte[] buffer = new byte[1024];
            int len;
            FileInputStream inputStream = new FileInputStream(uploadFile);
            while ((len = inputStream.read(buffer)) > 0) {
                outStream.write(buffer, 0, len);
            }
            inputStream.close();
            outStream.write("\r\n".getBytes());
        }
        //?
        outStream.write(endLine.getBytes());
        outStream.flush();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                socket.getInputStream()));
        if (!reader.readLine().startsWith("HTTP/1.1 200 OK")) {//web?200200?
            return false;
        }
        String line;
        while ((line = reader.readLine()) != null) {
            //http?
        }
        reader.close();
        outStream.close();
        socket.close();
        return true;
    }
}

Related Tutorials