日期:2014-05-17  浏览次数:20710 次

Connection timed out: connect 在线等!!!!!!!
package com.zdvictory.wjj.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
/**
 * 
 * @author huoyutu
 *
 */
public class Tools {
private String sessionId;
// private Tools(){}  
// private static final Tools tool=new Tools();  
// public static Tools getInstance() {  
// return tool;  
// }  

public boolean makeHtml(String loginUrl, String username, String password, String url, String filePath, String chartset) {
HttpURLConnection huc = null;
BufferedReader br = null;
BufferedWriter bw = null;
try {
if(this.getSessionId()==null || "".equals(this.getSessionId())){
this.sendLoginRequest(loginUrl, username, password);
}
huc = (HttpURLConnection) new URL(url).openConnection();
huc.setRequestProperty("Cookie",this.getSessionId());
huc.connect();

InputStream stream = huc.getInputStream();
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), chartset));
br = new BufferedReader(new InputStreamReader(stream, chartset));
String line;
while ((line = br.readLine()) != null) {
if (line.trim().length() > 0) {
bw.write(line);
bw.newLine();
}
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
br.close();
bw.close();
huc.disconnect();
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
return true;
}

public void sendLoginRequest(String url,String username,String password) throws IOException {
URL loginUrl = new URL(url);
  HttpURLConnection connection = (HttpURLConnection) loginUrl.openConnection(); 
  // Output to the connection. Default is
  // false, set to true because post
  // method must write something to the
  // connection
  // 设置是否向connection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true
  connection.setDoOutput(true);
  // Read from the connection. Default is true.
  connection.setDoInput(true);
  // Set the post method. Default is GET
  connection.setRequestMethod("POST");
  // Post cannot use caches
  // Post 请求不能使用缓存
connection.setUseCaches(false);
 
// This method takes effects to
// every instances of this class.
// URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。
// connection.setFollowRedirects(true);
 
// This methods only
// takes effacts to this
// instance.
// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
connection.setInstanceFollowRedirects(false);
 
// Set the content type to urlencoded,
// because we will write
// some URL-encoded content to the
// connection. Settings above must be set before connect!
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
// 意思是正文是u