Android---构建一个自己的网络框架(四)

Android---构建一个自己的网络框架以及源码

第四,执行网络请求

使用系统HttpURLConnection执行网络请求。

public class NetworkManager {

	private int connectTimeout = 60 * 1000 * 2;
	private int readTimeout = 60 * 1000 * 2;
	Context mContext;

	public static final boolean isLog = true;

	public NetworkManager(Context context, int second) {
		readTimeout *= second;
		this.mContext = context;
		setDefaultHostnameVerifier();
	}

	public NetworkManager(Context context) {
		this.mContext = context;
		setDefaultHostnameVerifier();
	}


	public void detectProxy() {
		ConnectivityManager cm = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
	}

	private void setDefaultHostnameVerifier() {
		HostnameVerifier hv = new HostnameVerifier() {
			public boolean verify(String hostname, SSLSession session) {
				return true;
			}
		};

		HttpsURLConnection.setDefaultHostnameVerifier(hv);
	}

	public String SendAndWaitXMLResponse(String strReqData, String strUrl) {
		if (isLog) {
			Global.debug("\r\nReqUrl:" + strUrl);
			Global.debug("ReqData:" + strReqData);
		}
		detectProxy();

		String strResponse = null;

		return strResponse;
	}

	public String SendAndWaitGetResponse(String strReqData, String strUrl) {
		if (isLog) {
			Global.debug("\r\nReqUrl:" + strUrl + "?" + strReqData);
			Global.debug("加密前ReqData:" + strReqData);
		}
		detectProxy();

		String strResponse = null;
		HttpURLConnection conn = null;

		try {
			URL mURL = new URL(strUrl + "?" + strReqData);                       // 创建一个URL对象
			conn = (HttpURLConnection) mURL.openConnection(); // 获取HttpURLConnection对象
			conn.setRequestMethod("GET");                   // 设置请求方法为post
			conn.setReadTimeout(10000);                       // 设置读取超时为5秒
			conn.setConnectTimeout(30000);// 设置连接网络超时为20秒
			setHeader(conn, "");  //  设置请求头

			int responseCode = conn.getResponseCode();        // 调用此方法就不必再使用.connect()方法
			if (responseCode == 200) {
				InputStream is = conn.getInputStream();
				strResponse = getStringFromInputStream(is);
				return strResponse;
			} else
				throw new NetworkErrorException("response status is "+responseCode);

		} catch (Exception e) {
			Global.debug(e);
		}

		if (isLog) {
			Global.debug("Resp:" + strResponse + "\r\n");
		}
		return strResponse;
	}

	public String SendAndWaitResponse(String strReqData, String strUrl) {
		if (isLog) {
			Global.debug("请求地址:" + strUrl);
			Global.debug("加密前ReqData:" + strReqData);
		}
		detectProxy();

		String strResponse = null;

		HttpURLConnection conn = null;
		try {
			URL mURL = new URL(strUrl);                       // 创建一个URL对象
			conn = (HttpURLConnection) mURL.openConnection(); // 获取HttpURLConnection对象
			conn.setRequestMethod("POST");                   // 设置请求方法为post
			conn.setReadTimeout(10000);                       // 设置读取超时为10秒
			conn.setConnectTimeout(30000);// 设置连接网络超时为20秒
			setHeader(conn, "");  //  设置请求头
			String data = AESEncryptorUtil.encryptToString(Global.ENCYPTKEY, Global.ENCYPTOFFSET, strReqData);
			Global.debug("加密后ReqData:" + data);
			byte[] writebytes = data.getBytes();
			conn.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
			Global.debug("请求头:"+conn.getRequestProperties());
			conn.setDoOutput(true);                          // 设置此方法,允许向服务器输出内容
			DataOutputStream dos=new DataOutputStream(conn.getOutputStream());
//			OutputStream out = conn.getOutputStream();        // 获得一个输出流,向服务器写数据

			dos.write(writebytes);                         // GET方式不需要
			dos.flush();
			dos.close();
			int responseCode = conn.getResponseCode();        // 调用此方法就不必再使用.connect()方法
			if (responseCode == 200) {
				InputStream is = conn.getInputStream();
				strResponse = getStringFromInputStream(is);
				return strResponse;
			} else
				throw new NetworkErrorException("response status is "+responseCode);

		} catch (Exception e) {
			Global.debug(e);
		}

		if (isLog) {
			Global.debug("Resp:" + strResponse + "\r\n");
		}
		return strResponse;
	}

	private void setHeader(HttpURLConnection conn, String req) {
		conn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
		conn.setRequestProperty("Charset", "UTF-8");
		conn.setRequestProperty("Content-Type", "application/json;charset=utf-8"); //text/plain
	}

	private String getStringFromInputStream(InputStream is) throws IOException {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = -1;
		while ((len = is.read(buffer)) != -1)
			os.write(buffer, 0, len);
		is.close();
		String state = os.toString();
		os.close();
		return state;
	}
}

可以对请求参数进行加密,如AES加密:

public class AESEncryptorUtil {

    private final static String KEY_ALGORITHM = "AES";
    private final static String CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";
    private final static String DEFAULT_ENCODING = "UTF-8";

    public static String encryptToString(String key, String offset, String content) throws Exception {
        return Base64.encodeToString(encryptProcess(key, offset, content, DEFAULT_ENCODING), Base64.DEFAULT);
    }

    public static String decryptToString(String key, String offset, String content) throws Exception {
        return new String(decryptProcess(key, offset, Base64.decode(content.getBytes(), Base64.DEFAULT)), DEFAULT_ENCODING);
    }

    private static byte[] encryptProcess(String key, String offset, String content, String encoding) throws Exception {
        byte[] data = {};
        Key secretKey = new SecretKeySpec(key.getBytes(), KEY_ALGORITHM);
        byte[] byteContent = content.getBytes(encoding);
        IvParameterSpec iv = new IvParameterSpec(offset.getBytes());
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        data = cipher.doFinal(byteContent);
        return data;
    }

    private static byte[] decryptProcess(String key, String offset, byte[] content) throws Exception {
        byte[] data = {};
        Key secretKey = new SecretKeySpec(key.getBytes(), KEY_ALGORITHM);
        IvParameterSpec iv = new IvParameterSpec(offset.getBytes());
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        return cipher.doFinal(content);
    }

    public static void main(String[] args) throws Exception {
        String key = "1234567890123456";
        String offset = "1111111111111111";
        String content = "{\n" +
                "    \"name\": \"BeJson\",\n" +
                "    \"url\": \"http://www.bejson.com\",\n" +
                "    \"page\": 88,\n" +
                "    \"isNonProfit\": true,\n" +
                "    \"address\": {\n" +
                "        \"street\": \"科技园路.\",\n" +
                "        \"city\": \"江苏苏州\",\n" +
                "        \"country\": \"中国\"\n" +
                "    },\n" +
                "    \"links\": [\n" +
                "        {\n" +
                "            \"name\": \"Google\",\n" +
                "            \"url\": \"http://www.google.com\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"name\": \"Baidu\",\n" +
                "            \"url\": \"http://www.baidu.com\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"name\": \"SoSo\",\n" +
                "            \"url\": \"http://www.SoSo.com\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        String sStr = encryptToString(key, offset, content);
        System.out.println(sStr);
        String data = decryptToString(key, offset, sStr);
        System.out.println(data);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值