当前位置:首页 > 开发 > 系统架构 > 架构 > 正文

架构师之httpurlconnection----------读取和发送(流读取效率通用类)

发表于: 2015-06-17   作者:nannan408   来源:转载   浏览:
摘要: 1.前言.    如题. 2.代码. /* * Copyright (c) 2015, S.F. Express Inc. All rights reserved. */ package com.test.test.test.send; import java.io.IOException; import java.io.InputStream
1.前言.
   如题.
2.代码.
/* 
 * Copyright (c) 2015, S.F. Express Inc. All rights reserved.
 */
package com.test.test.test.send;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.test.test.test.util.SendConstants;

/**
 * 
 * 描述:httpurl的http发送
 *  作者:李俊南
 */
public class TestHttpMultiSendManagerTest implements TestSendManager {
	private Logger logger = LoggerFactory
			.getLogger(DrpHttpMultiSendManagerTest.class);

	@Override
	public String send(String url, String port, String content, String type) {
		switch (type) {
		case SendConstants.SEND_RES:
			return sendRes(url, content);
		case SendConstants.SEND_NO_RES:
			return sendNoRes(url, content);
		case SendConstants.SEND_ASY_RES:
			return sendAsyRes(url, content);
		case SendConstants.SEND_ASY_NO_RES:
			return sendAsyNoRes(url, content);
		default:
		}
		return null;
	}

	public String Object(String url, String content, String type) {
		return send(url, "", content, type);
	}

	/**
	 * ͬ�发送
	 * 
	 * @param url
	 * @param content
	 * @return String
	 * @throws ProtocolException
	 * @throws MalformedURLException
	 */
	public String sendRes(String sendUrl, String content) {

		// URL url = new URL("http://localhost:8083/test");

		URL url = null;
		URLConnection rulConnection = null;
		HttpURLConnection httpUrlConnection = null;
		try {
			url = new URL(sendUrl + SendConstants.SEND_PARAM_NAME
					+ URLEncoder.encode(content, "utf8"));
			rulConnection = url.openConnection();
			httpUrlConnection = (HttpURLConnection) rulConnection;
			httpUrlConnection.setDoOutput(true);
			httpUrlConnection.setDoInput(true);
			httpUrlConnection.setUseCaches(false);
			httpUrlConnection.setConnectTimeout(5000);
			httpUrlConnection.setReadTimeout(5000);

			httpUrlConnection.setRequestProperty("Content-type", "text/html");
			httpUrlConnection.setRequestMethod("POST");

			httpUrlConnection.connect();
			try (InputStream inStrm = httpUrlConnection.getInputStream();) {
//				byte[] b = new byte[inStrm.available()];
//				int len = 0;
//				StringBuilder resultContent = new StringBuilder();
//				while (len < inStrm.available()) {
//					len += inStrm.read(b, len, inStrm.available() - len);
//					resultContent.append(new String(b));
//				}
//				String result = resultContent.toString();
				String result=getEncodedData(inStrm);
				inStrm.close();
				logger.info("返回:" + result);
				return result;
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (null != httpUrlConnection) {
				httpUrlConnection.disconnect();
			}

		}
	}
	/**
     * 此方法用于从输入流中获取数据
     * 
     * @param is 接收来自客户端socket对应的输入流
     * @return 返回endodedData
     * @throws IOException 抛出的异常,统一在run函数处理
     */
    private String getEncodedData(InputStream is) throws IOException {
        byte[] maxBuffer = new byte[1024 * 64];
        int length = 0;
        int lengthTemp = 0;
        while (-1 != (lengthTemp = is.read(maxBuffer))) { // read方法并不保证一次能读取1024*64个字节
            length += lengthTemp;
            if (length >= 1024 * 64) {
                logger.debug("读入的数据超过1024 * 64");
                break;
            }
        }

        byte[] endodedData = new byte[length];
        System.arraycopy(maxBuffer, 0, endodedData, 0, length);

        //logger.info("receiveData:" + bytesToHexString(endodedData) + '\n');
        return new String(endodedData);
    }
    public static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv+" ");
        }
        return stringBuilder.toString();
    }
	public String sendNoRes(String url, String content) {
		return null;
	}

	public String sendAsyRes(String url, String content) {
		return null;
	}

	public String sendAsyNoRes(String url, String content) {
		return null;
	}


}




3.注意事项.
   (1)available读法有点不可靠,可能造成数据丢失,所以应该用字节读取办法来,代码中注释的available可对比一下替换的内容.
   (2)字节转字符直接用new String()就可以了.

架构师之httpurlconnection----------读取和发送(流读取效率通用类)

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

推荐文章
编辑推荐
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号