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();
			
		}
	}

}

阅读更多
个人分类: 类和对象
上一篇python 脚本开机自启动
下一篇python远程连接
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭