HttpURLConnection不安全说明

测试SocketTimeoutException异常。

测试方法一:设置将url改为一个不存在的url:“http://test.com”,发现在OutputStream out = conn.getOutputStream();就会抛出异常,

测试方法二:使服务器Thread.sleep(3000);   此时InputStream inStream = conn.getInputStream();会抛出异常,但是此时数据已经发送到服务端,会导致数据重复发送。

package com.mobile263.clhttpclient;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;


public class ClClient {

	private static Logger logger = Logger.getLogger(ClClient.class);
	
	public static void main(String[] args) {

		BasicConfigurator.configure();
		String sURI = "http://wfhak1111.com";
		String req = "im client hello";
		long startTime;
		long endTime;
		Long difference;
		int processingTime;
		
		byte[] b = new byte[1024];
		int n = 0;
		startTime = System.currentTimeMillis();
		logger.info("hello");
		
		try {
			URL url = new URL(sURI);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setConnectTimeout(3000);
			conn.setReadTimeout(3000);
			
			
			OutputStream out = conn.getOutputStream();
			out.write(req.getBytes());
			out.close();
			
			InputStream inStream = conn.getInputStream();
			StringBuffer outBuf = new StringBuffer();
			while ((n = inStream.read(b)) > 0) {
				outBuf.append(new String(b, 0, n));
			}
			conn.disconnect();
			endTime = System.currentTimeMillis();
			difference = new Long(endTime - startTime);
			processingTime = difference.intValue();
//			

			String ret = new String(outBuf.toString().getBytes(), "utf-8");

			
		}catch (SocketTimeoutException e) {
			
			System.out.println("SocketTimeoutException");
			TaskClReq clTarget = new TaskClReq(sURI,req);
			Thread  clThread = new Thread(clTarget);
			clThread.start();
		}
		catch (Throwable e) {
			System.out.println("Throwable");
			e.printStackTrace();
			
		}
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值