首页 > 技术文章 > MyIfmHttpClient

tonggc1668 2017-09-15 11:04 原文

package com.yd.ifm.client.caller.util.http;

import java.util.Map;

import com.yd.ifm.client.caller.model.ResponseData;
import com.yd.ifm.client.caller.util.http.HttpEnum.ContentTypeEnum;

public interface IfmHttpClient {
    
    /**
     * 发送post数据
     * 200为正常的业务数据,202为IfmClient的一些授权不通过或者异常信息
     * headerMap 需要放在Http客户端的header中
     * data 为body中的业务数据
     * @param strUrlPath
     * @param params
     * @param encode
     * @return
     */
    ResponseData postData(String strUrlPath, Map<String, String> headerMap, String data, String encode, ContentTypeEnum contentType);
}
package com.yundaex.wms.config.clent;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import org.apache.log4j.Logger;

import com.yd.ifm.client.caller.model.ResponseData;
import com.yd.ifm.client.caller.util.http.HttpEnum.ContentTypeEnum;
import com.yd.ifm.client.caller.util.http.HttpEnum.RequestMethodEnum;
import com.yd.ifm.client.caller.util.http.IfmHttpClient;

/**
 * <pre>
 *   Title: MyIfmHttpClient.java
 *   Description: 
 *   Copyright: yundaex.com Copyright (c) 2017
 *   Company: 上海韵达货运有限公司
 * </pre>
 * 
 * @author tonglele
 * @version 1.0
 * @date 2017年9月15日
 */
public class MyIfmHttpClient implements IfmHttpClient {
    private final static Logger log = Logger.getLogger(MyIfmHttpClient.class);
    private final static String CONTENT_TYPE = "Content-Type";
    private final static String CONTENT_LENGTH = "Content-Length";
    private final static String ZERO = "0";

    
    @Override
    public ResponseData postData(String strUrlPath, Map<String, String> params, String data, String encode,
            ContentTypeEnum contentType) {
        byte[] bodybyte = getRequestData(data, encode);// 获得请求体
        ResponseData responsedata = new ResponseData();
        OutputStream outputStream = null;
        InputStream inptStream = null;
        try {
            URL url = new URL(strUrlPath);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setConnectTimeout(20000); // 设置连接超时时间
            httpURLConnection.setDoInput(true); // 打开输入流,以便从服务器获取数据
            httpURLConnection.setDoOutput(true); // 打开输出流,以便向服务器提交数据
            httpURLConnection.setRequestMethod(RequestMethodEnum.POST.getMethod()); // 设置以Post方式提交数据
            httpURLConnection.setUseCaches(false); // 使用Post方式不能使用缓存
            httpURLConnection.setReadTimeout(60000); // 设置读取数据的超时时间
            // 添加控制权限的header
            addHeader(params, httpURLConnection);
            // 设置请求体的类型是文本类型
            httpURLConnection.setRequestProperty(CONTENT_TYPE, contentType.getType());
            // 设置请求体的长度
            httpURLConnection.setRequestProperty(CONTENT_LENGTH,
                    bodybyte == null ? ZERO : String.valueOf(bodybyte.length));
            // 获得输出流,向服务器写入数据
            outputStream = httpURLConnection.getOutputStream();
            if (bodybyte != null)
                outputStream.write(bodybyte);
            outputStream.flush();

            int responsecode = httpURLConnection.getResponseCode(); // 获得服务器的响应码
            responsedata.setError_code(responsecode);
            // 200表示有正常的业务数据 202则表示有callee的异常
            if (responsecode == HttpURLConnection.HTTP_OK || responsecode == 202) {
                inptStream = httpURLConnection.getInputStream();
                responsedata.setData(dealResponseResult(inptStream));
            }
        } catch (IOException e) {
            log.error("error while using IfmHttpUtil" + e);
            return responsedata;
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.error("error while using IfmHttpUtil" + e);
                }
            }
            if (inptStream != null) {
                try {
                    inptStream.close();
                } catch (IOException e) {
                    log.error("error while using IfmHttpUtil" + e);
                }
            }
        }
        return responsedata;
    }

    private byte[] getRequestData(String content, String encode) {
        byte[] result = null;
        try {
            if (content != null)
                result = content.getBytes(encode);
        } catch (UnsupportedEncodingException e) {
            log.error("error while using IfmHttpUtil" + e);
        }
        return result;
    }

    /**
     * 处理服务器返回结果
     * 
     * @param inputStream
     *            输入流
     * @return 返回处理后的String 字符串
     */
    private String dealResponseResult(InputStream inputStream) {
        String resultData = null; // 存储处理结果
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
        try {
            while ((len = inputStream.read(data)) != -1) {
                byteArrayOutputStream.write(data, 0, len);
            }
            resultData = new String(byteArrayOutputStream.toByteArray(), "utf-8");
        } catch (IOException e) {
            log.error("error while using IfmHttpUtil" + e);
        }
        return resultData;
    }

    /**
     * 将权限信息放在header中
     * 
     * @param headerMapper
     * @param connection
     */
    private void addHeader(Map<String, String> headerMapper, HttpURLConnection connection) {
        for (Map.Entry<String, String> entry : headerMapper.entrySet()) {
            connection.addRequestProperty(entry.getKey(), entry.getValue());
        }
    }

}

 

推荐阅读