java 来自http://ria10.hatenablog.com/entry/20121222/1356153903

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 来自http://ria10.hatenablog.com/entry/20121222/1356153903相关的知识,希望对你有一定的参考价值。

public class HttpClientForPost extends HttpClient {
    private static final String TAG = HttpClientForPost.class.getSimpleName();
    public static final String HOST = "http://api.example.com:3000"; 
    public static final String CRLF = "\r\n";
    public static final String BOUNDARY = "---*#asdkfjaewaefa#";
    public static final String TWO_HYPHEN = "--";

    private Map<String, String> textDataMap = new HashMap<String, String>();
    private ArrayList<MultiPartFile> multiPartFileArrayList = new ArrayList<MultiPartFile>();
    private StringBuilder dummyBody = new StringBuilder();

    protected HttpClientForPost(URL url) throws IOException {
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setReadTimeout(10 * 1000);
        conn.setConnectTimeout(10 * 1000);
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + HttpClientForPost.BOUNDARY);
    }

    public void addTextValue(String key, String value) {
        textDataMap.put(key, value);
    }

    public Map<String, String> getTextDataMap() {
        return textDataMap;
    }

    public void addFile(MultiPartFile multiPartFile){
        multiPartFileArrayList.add(multiPartFile);
    }

    public ArrayList<MultiPartFile> getMultiPartFileArrayList() {
        return multiPartFileArrayList;
    }

    private String createTextBody() throws UnsupportedEncodingException {
        StringBuilder body = new StringBuilder();
        body.append(CRLF);

        for (Map.Entry<String, String> entry : textDataMap.entrySet()) {
            body
                .append(TWO_HYPHEN).append(BOUNDARY).append(CRLF)
                .append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"").append(CRLF)
                .append(CRLF)
                .append(entry.getValue()).append(CRLF);
        }

        return body.toString();
    }

    private int write(BufferedOutputStream out, String string) throws IOException {
        dummyBody.append(string);
        out.write(string.getBytes("UTF-8"));
        return string.length();
    }

    private int write(BufferedOutputStream out, byte[] bytes) throws IOException {
        dummyBody.append("#");
        out.write(bytes);
        return bytes.length;
    }

    public HttpResponse post() throws IOException, NoParameterException, HttpPostException {
        BufferedOutputStream out =  new BufferedOutputStream(conn.getOutputStream());
        int contentLength = 0;
        contentLength += write(out, CRLF);

        if ( !parameterExists() ) {
            throw new NoParameterException();
        }

        if (textDataMap.size() > 0) {
            contentLength += write(out, createTextBody());
        }

        out.flush();

        for (MultiPartFile multiPartFile : multiPartFileArrayList) {
            Log.d(TAG, "size:" + multiPartFileArrayList.size());
            contentLength += write(out, (TWO_HYPHEN + BOUNDARY + CRLF));
            String header = "Content-Disposition: form-data; name=\"" + multiPartFile.getName() + "\"; filename=\"" + multiPartFile.getFileName() + "\"" + CRLF +
                "Content-Type: " + multiPartFile.getMimeType() + CRLF;


            contentLength += write(out, header);
            contentLength += write(out, CRLF);

            InputStream inputStream = multiPartFile.getInputStream();
            byte[] input = new byte[inputStream.available()];
            while(inputStream.read(input) > -1) {
                contentLength += input.length;
                write(out, input);
            }

            contentLength += write(out, CRLF);

        }

        contentLength += write(out, (TWO_HYPHEN + BOUNDARY + TWO_HYPHEN + CRLF));

        Log.d(TAG, dummyBody.toString());

        out.flush();
        out.close();

        int responseCode = conn.getResponseCode();
        String responseMessage = conn.getResponseMessage();
        if (responseCode != 201) {
            String errorMessage = "responseCode: " + responseCode + "\nresponseMessage: " + responseMessage;
            Log.e(TAG, errorMessage);
            throw new HttpPostException(errorMessage);
        }
        InputStream in = new BufferedInputStream(conn.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line).append("\n");
        }

        return new HttpResponse(responseCode, responseMessage, response.toString());
    }

    public void disconnect() {
        conn.disconnect();
    }

    public URL getURL() {
        return conn.getURL();
    }

    private boolean parameterExists() {
        return multiPartFileArrayList.size() > 0 || textDataMap.size() > 0;
    }

    public static String wrapParameterName(String wrap, String param) {
        return wrap + "[" + param + "]";
    }


}

public class HttpResponse {
    private static final String TAG = HttpResponse.class.getSimpleName();

    private int responseCode;
    private String responseMessage;
    private String responseBody;

    public HttpResponse(int responseCode, String responseMessage, String responseBody) {
        this.responseCode = responseCode;
        this.responseMessage = responseMessage;
        this.responseBody = responseBody;
    }

    public int getResponseCode() {
        return responseCode;
    }

    public String getResponseMessage() {
        return responseMessage;
    }

    public String getResponseBody() {
        return responseBody;
    }
}

public class MultiPartFile {
    private static final String TAG = MultiPartFile.class.getSimpleName();
    private String name;
    private String fileName;
    private InputStream inputStream;

    public MultiPartFile(String name, String fileName, InputStream is) {
        this.name = name;
        this.fileName = fileName;
        this.inputStream = is;
    }

    public String getMimeType() {
        ExtensionMimeDetector detector = new ExtensionMimeDetector();
        Object[] mimeTypes = detector.getMimeTypes(fileName).toArray();
        MimeType mimeType = (MimeType)mimeTypes[0];

        return mimeType.toString();
    }

    public String getName() {
        return name;
    }

    public String getFileName() {
        return fileName;
    }

    public InputStream getInputStream() {
        return inputStream;
    }
}

以上是关于java 来自http://ria10.hatenablog.com/entry/20121222/1356153903的主要内容,如果未能解决你的问题,请参考以下文章

来自java的流插入:templateSuffix

来自客户端的 Java (Tomcat) websocket 参数

Java:没有来自外部类的 ArrayList 修改

java 来自http://javabeat.net/java-getresourcestream/

Java:字体不加载(来自外部文件)

java Java中的缓存反射访问(来自Spring Framework代码库)