com.micro.http.MicroRequestParams.java Source code

Java tutorial

Introduction

Here is the source code for com.micro.http.MicroRequestParams.java

Source

/*
 * Copyright (C) 2012 Chengel_HaltuD
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.micro.http;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import com.micro.http.entity.HttpMultipartMode;
import com.micro.http.entity.MultipartEntity;

//TODO: Auto-generated Javadoc
/**
 * 
 * @ClassName: MicroRequestParams
 * @Description: ??Http?
 * @AuthorChengel_HaltuD
 * @Date2015-5-30 ?2:52:56
 * @version V1.0
 *
 */
public class MicroRequestParams {

    /** url?. */
    protected ConcurrentHashMap<String, String> urlParams;
    /** ?. */
    protected ConcurrentHashMap<String, ContentBody> fileParams;
    private MultipartEntity multiPart = null;
    private final static int boundaryLength = 32;
    private final static String boundaryAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
    private String boundary;

    /**
     * auto generate boundary string
     * 
     * @return a boundary string
     */
    private String getBoundary() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < boundaryLength; ++i)
            sb.append(boundaryAlphabet.charAt(random.nextInt(boundaryAlphabet.length())));
        return sb.toString();
    }

    /**
     * @return get MultipartEntity (apache)
     */
    public MultipartEntity getMultiPart() {
        return multiPart;
    }

    /**
     * default boundary is auto generate {@link #getBoundary()}
     */
    public MicroRequestParams() {
        super();
        boundary = getBoundary();
        urlParams = new ConcurrentHashMap<String, String>();
        fileParams = new ConcurrentHashMap<String, ContentBody>();
        multiPart = new MultipartEntity(HttpMultipartMode.STRICT, boundary, Charset.forName("UTF-8"));
    }

    /**
     * @return multipart boundary string
     */
    public String boundaryString() {
        return boundary;
    }

    /**
     * ?
     * 
     * @param attr
     *            ??
     * @param file
     *            
     */
    public void put(String attr, File file) {
        if (attr != null && file != null) {
            fileParams.put(attr, new FileBody(file));
        }

    }

    /**
     * byte[]?
     * 
     * @param attr
     *            ??
     * @param fileName
     *            ??
     * @param data
     *            
     */
    public void put(String attr, String fileName, byte[] data) {
        if (attr != null && fileName != null) {
            fileParams.put(attr, new ByteArrayBody(data, fileName));
        }
    }

    /**
     * String?
     * 
     * @param attr
     * @param str
     */
    public void put(String attr, String value) {
        try {
            if (attr != null && value != null) {
                urlParams.put(attr, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * ??.
     * 
     * @return the param string
     */
    public String getParamString() {
        List<BasicNameValuePair> paramsList = new LinkedList<BasicNameValuePair>();
        for (ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
            paramsList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        return URLEncodedUtils.format(paramsList, HTTP.UTF_8);
    }

    /**
     * ??.
     * 
     * @return the params list
     */
    public List<BasicNameValuePair> getParamsList() {
        List<BasicNameValuePair> paramsList = new LinkedList<BasicNameValuePair>();
        for (ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
            paramsList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        return paramsList;
    }

    /**
     * 
     * ?HttpEntity.
     */
    public HttpEntity getEntity() {

        if (fileParams.isEmpty()) {
            // ??
            return createFormEntity();
        } else {
            // ??
            return createMultipartEntity();
        }
    }

    /**
     * HttpEntity.
     * 
     * @return the http entity
     */
    public HttpEntity createFormEntity() {
        try {
            return new UrlEncodedFormEntity(getParamsList(), HTTP.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * ??HttpEntity.
     * 
     * @return
     * @throws IOException
     */
    private HttpEntity createMultipartEntity() {

        try {
            // Add string params
            for (ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
                multiPart.addPart(entry.getKey(), new StringBody(entry.getValue(), Charset.forName("UTF-8")));
            }

            // Add file params
            for (ConcurrentHashMap.Entry<String, ContentBody> entry : fileParams.entrySet()) {
                ContentBody contentBody = entry.getValue();
                multiPart.addPart(entry.getKey(), contentBody);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return multiPart;
    }

    /**
     * ?url?.
     * 
     * @return the url params
     */
    public ConcurrentHashMap<String, String> getUrlParams() {
        return urlParams;
    }

    /**
     * ??.
     * 
     * @return the file params
     */
    public ConcurrentHashMap<String, ContentBody> getFileParams() {
        return fileParams;
    }

    /**
     * ????.
     *
     * @return the string
     */
    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        for (ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
            if (result.length() > 0)
                result.append("&");

            result.append(entry.getKey());
            result.append("=");
            result.append(entry.getValue());
        }

        return result.toString();
    }
}