
2009年6月29日
**
* <pre>
* Title: HttpRequestProxy.java
* Project: HP-Common
* Type: com.hengpeng.common.web.HttpRequestProxy
* Author: benl
* Create: 2007-7-3 上午03:07:07
* Copyright: Copyright (c) 2007
* Company:
* <pre>
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
/**
* <pre>
* HTTP請求代理類
* </pre>
*
* @author benl
* @version 1.0, 2007-7-3
*/
public class HttpRequestProxy
{
/**
* 連接超時
*/
private static int connectTimeOut = 5000;
/**
* 讀取數據超時
*/
private static int readTimeOut = 10000;
/**
* 請求編碼
*/
private static String requestEncoding = "GBK";
private static Logger logger = Logger.getLogger(HttpRequestProxy.class);
/**
* <pre>
* 發送帶參數的GET的HTTP請求
* </pre>
*
* @param reqUrl HTTP請求URL
* @param parameters 參數映射表
* @return HTTP響應的字符串
*/
public static String doGet(String reqUrl, Map parameters,
String recvEncoding)
{
HttpURLConnection url_con = null;
String responseContent = null;
try
{
StringBuffer params = new StringBuffer();
for (Iterator iter = parameters.entrySet().iterator(); iter
.hasNext();)
{
Entry element = (Entry) iter.next();
params.append(element.getKey().toString());
params.append("=");
params.append(URLEncoder.encode(element.getValue().toString(),
HttpRequestProxy.requestEncoding));
params.append("&");
}
if (params.length() > 0)
{
params = params.deleteCharAt(params.length() - 1);
}
URL url = new URL(reqUrl);
url_con = (HttpURLConnection) url.openConnection();
url_con.setRequestMethod("GET");
System.setProperty("sun.net.client.defaultConnectTimeout", String
.valueOf(HttpRequestProxy.connectTimeOut));// (單位:毫秒)jdk1.4換成這個,連接超時
System.setProperty("sun.net.client.defaultReadTimeout", String
.valueOf(HttpRequestProxy.readTimeOut)); // (單位:毫秒)jdk1.4換成這個,讀操作超時
// url_con.setConnectTimeout(5000);//(單位:毫秒)jdk
// 1.5換成這個,連接超時
// url_con.setReadTimeout(5000);//(單位:毫秒)jdk 1.5換成這個,讀操作超時
url_con.setDoOutput(true);
byte[] b = params.toString().getBytes();
url_con.getOutputStream().write(b, 0, b.length);
url_con.getOutputStream().flush();
url_con.getOutputStream().close();
InputStream in = url_con.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in,
recvEncoding));
String tempLine = rd.readLine();
StringBuffer temp = new StringBuffer();
String crlf=System.getProperty("line.separator");
while (tempLine != null)
{
temp.append(tempLine);
temp.append(crlf);
tempLine = rd.readLine();
}
responseContent = temp.toString();
rd.close();
in.close();
}
catch (IOException e)
{
logger.error("網絡故障", e);
}
finally
{
if (url_con != null)
{
url_con.disconnect();
}
}
return responseContent;
}
/**
* <pre>
* 發送不帶參數的GET的HTTP請求
* </pre>
*
* @param reqUrl HTTP請求URL
* @return HTTP響應的字符串
*/
public static String doGet(String reqUrl, String recvEncoding)
{
HttpURLConnection url_con = null;
String responseContent = null;
try
{
StringBuffer params = new StringBuffer();
String queryUrl = reqUrl;
int paramIndex = reqUrl.indexOf("?");
if (paramIndex > 0)
{
queryUrl = reqUrl.substring(0, paramIndex);
String parameters = reqUrl.substring(paramIndex + 1, reqUrl
.length());
String[] paramArray = parameters.split("&");
for (int i = 0; i < paramArray.length; i++)
{
String string = paramArray[i];
int index = string.indexOf("=");
if (index > 0)
{
String parameter = string.substring(0, index);
String value = string.substring(index + 1, string
.length());
params.append(parameter);
params.append("=");
params.append(URLEncoder.encode(value,
HttpRequestProxy.requestEncoding));
params.append("&");
}
}
params = params.deleteCharAt(params.length() - 1);
}
URL url = new URL(queryUrl);
url_con = (HttpURLConnection) url.openConnection();
url_con.setRequestMethod("GET");
System.setProperty("sun.net.client.defaultConnectTimeout", String
.valueOf(HttpRequestProxy.connectTimeOut));// (單位:毫秒)jdk1.4換成這個,連接超時
System.setProperty("sun.net.client.defaultReadTimeout", String
.valueOf(HttpRequestProxy.readTimeOut)); // (單位:毫秒)jdk1.4換成這個,讀操作超時
// url_con.setConnectTimeout(5000);//(單位:毫秒)jdk
// 1.5換成這個,連接超時
// url_con.setReadTimeout(5000);//(單位:毫秒)jdk 1.5換成這個,讀操作超時
url_con.setDoOutput(true);
byte[] b = params.toString().getBytes();
url_con.getOutputStream().write(b, 0, b.length);
url_con.getOutputStream().flush();
url_con.getOutputStream().close();
InputStream in = url_con.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in,
recvEncoding));
String tempLine = rd.readLine();
StringBuffer temp = new StringBuffer();
String crlf=System.getProperty("line.separator");
while (tempLine != null)
{
temp.append(tempLine);
temp.append(crlf);
tempLine = rd.readLine();
}
responseContent = temp.toString();
rd.close();
in.close();
}
catch (IOException e)
{
logger.error("網絡故障", e);
}
finally
{
if (url_con != null)
{
url_con.disconnect();
}
}
return responseContent;
}
/**
* <pre>
* 發送帶參數的POST的HTTP請求
* </pre>
*
* @param reqUrl HTTP請求URL
* @param parameters 參數映射表
* @return HTTP響應的字符串
*/
public static String doPost(String reqUrl, Map parameters,
String recvEncoding)
{
HttpURLConnection url_con = null;
String responseContent = null;
try
{
StringBuffer params = new StringBuffer();
for (Iterator iter = parameters.entrySet().iterator(); iter
.hasNext();)
{
Entry element = (Entry) iter.next();
params.append(element.getKey().toString());
params.append("=");
params.append(URLEncoder.encode(element.getValue().toString(),
HttpRequestProxy.requestEncoding));
params.append("&");
}
if (params.length() > 0)
{
params = params.deleteCharAt(params.length() - 1);
}
URL url = new URL(reqUrl);
url_con = (HttpURLConnection) url.openConnection();
url_con.setRequestMethod("POST");
System.setProperty("sun.net.client.defaultConnectTimeout", String
.valueOf(HttpRequestProxy.connectTimeOut));// (單位:毫秒)jdk1.4換成這個,連接超時
System.setProperty("sun.net.client.defaultReadTimeout", String
.valueOf(HttpRequestProxy.readTimeOut)); // (單位:毫秒)jdk1.4換成這個,讀操作超時
// url_con.setConnectTimeout(5000);//(單位:毫秒)jdk
// 1.5換成這個,連接超時
// url_con.setReadTimeout(5000);//(單位:毫秒)jdk 1.5換成這個,讀操作超時
url_con.setDoOutput(true);
byte[] b = params.toString().getBytes();
url_con.getOutputStream().write(b, 0, b.length);
url_con.getOutputStream().flush();
url_con.getOutputStream().close();
InputStream in = url_con.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in,
recvEncoding));
String tempLine = rd.readLine();
StringBuffer tempStr = new StringBuffer();
String crlf=System.getProperty("line.separator");
while (tempLine != null)
{
tempStr.append(tempLine);
tempStr.append(crlf);
tempLine = rd.readLine();
}
responseContent = tempStr.toString();
rd.close();
in.close();
}
catch (IOException e)
{
logger.error("網絡故障", e);
}
finally
{
if (url_con != null)
{
url_con.disconnect();
}
}
return responseContent;
}
/**
* @return 連接超時(毫秒)
* @see com.hengpeng.common.web.HttpRequestProxy#connectTimeOut
*/
public static int getConnectTimeOut()
{
return HttpRequestProxy.connectTimeOut;
}
/**
* @return 讀取數據超時(毫秒)
* @see com.hengpeng.common.web.HttpRequestProxy#readTimeOut
*/
public static int getReadTimeOut()
{
return HttpRequestProxy.readTimeOut;
}
/**
* @return 請求編碼
* @see com.hengpeng.common.web.HttpRequestProxy#requestEncoding
*/
public static String getRequestEncoding()
{
return requestEncoding;
}
/**
* @param connectTimeOut 連接超時(毫秒)
* @see com.hengpeng.common.web.HttpRequestProxy#connectTimeOut
*/
public static void setConnectTimeOut(int connectTimeOut)
{
HttpRequestProxy.connectTimeOut = connectTimeOut;
}
/**
* @param readTimeOut 讀取數據超時(毫秒)
* @see com.hengpeng.common.web.HttpRequestProxy#readTimeOut
*/
public static void setReadTimeOut(int readTimeOut)
{
HttpRequestProxy.readTimeOut = readTimeOut;
}
/**
* @param requestEncoding 請求編碼
* @see com.hengpeng.common.web.HttpRequestProxy#requestEncoding
*/
public static void setRequestEncoding(String requestEncoding)
{
HttpRequestProxy.requestEncoding = requestEncoding;
}
public static void main(String[] args)
{
Map map = new HashMap();
map.put("actionType", "1");
// map.put("issueId", "33");
String temp = HttpRequestProxy.doPost("http://192.168.0.99/AgentPortal/autoHandler", map, "GBK");
System.out.println("返回的消息是:"+temp);
}
}
文章來源:
http://blog.163.com/ccbobo_cat/blog/static/320994622009616102329953
posted @
2009-07-16 10:23 C.B.K 閱讀(1811) |
評論 (1) |
編輯 收藏
/*
下面的程序說明了怎樣實現對象序列化和反序列化。它由實例化一個MyClass類的對象開始。該對象有三個實例變量,它們的類型分別是String,int和double。這是我們希望存儲和恢復的信息。
FileOutputStream被創建,引用了一個名為“serial”的文件。為該文件流創建一個ObjectOutputStream。ObjectOutputStream 的writeObject( )方法用來序列化對象。對象的輸出流被刷新和關閉。
然后,引用名為“serial”的文件創建一個FileInputStream類并為該文件創建一個ObjectInputStream類。ObjectInputStream 的readObject( )方法用來反序列化對象。然后對象輸入流被關閉。
注意MyClass被定義成實現Serializable接口。如果不這樣做,將會引發一個NotSerializableException異常。試圖做一些把MyClass實例變量聲明成transient的實驗。那些數據在序列化過程中不被保存
*/
import java.io.*;
class MyClass implements Serializable{
String s;
int i;
double d;
public MyClass (String s,int i,double d){
this.s = s;
this.i = i;
this.d = d;
}
public String toString(){
return "s=" + s + "; i=" + i + "; d=" + d;
}
}
class SerializationDemo{
public static void main(String[] args){
//Object serialization.
try{
MyClass object1 = new MyClass("Evan",9,9.9e10);
System.out.println("object1 : " +object1);
FileOutputStream fos = new FileOutputStream("serial");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object1);
oos.flush();
oos.close();
}catch(Exception e){
System.out.println("Exception during serialization :" + e);
System.exit(0);
}
//Object deserialization.
try{
MyClass object2 ;
FileInputStream fis = new FileInputStream("serial");
ObjectInputStream ois = new ObjectInputStream(fis);
object2 = (MyClass)ois.readObject();
ois.close();
System.out.println("object2 : " +object2);
}catch(Exception e){
System.out.println("Exception during serialization :" + e);
System.exit(0);
}
}
}
文章來源:
http://blog.163.com/ccbobo_cat/blog/static/320994622009616101541196
posted @
2009-07-16 10:16 C.B.K 閱讀(173) |
評論 (0) |
編輯 收藏
Java的serialization提供了一種持久化對象實例的機制。當持久化對象時,可能有一個特殊的對象數據成員,我們不想
用serialization機制來保存它。為了在一個特定對象的一個域上關閉serialization,可以在這個域前加上關鍵字transient。
transient是Java語言的關鍵字,用來表示一個域不是該對象串行化的一部分。當一個對象被串行化的時候,transient型變量的值不包括在串行化的表示中,然而非transient型的變量是被包括進去的。
文章來源:
http://blog.163.com/ccbobo_cat/blog/static/3209946220096161094144
posted @
2009-07-16 10:09 C.B.K 閱讀(158) |
評論 (0) |
編輯 收藏
匹配中文字符的正則表達式: [\u4e00-\u9fa5]
匹配雙字節字符(包括漢字在內): [^\x00-\xff]
應用:計算字符串的長度(一個雙字節字符長度計2,ASCII字符計1)
String.prototype.len=function(){return this.replace([^\x00-\xff]/g,"aa").length;}
匹配空行的正則表達式: \n[\s| ]*\r
匹配HTML標記的正則表達式: /<(.*)>.*<\/>|<(.*) \/>/
匹配首尾空格的正則表達式: (^\s*)|(\s*$)
應用:javascript中沒有像vbscript那樣的trim函數,我們就可以利用這個表達式來實現,如下:
String.prototype.trim = function() {
return this.replace(/(^\s*)|(\s*$)/g, "");
}
利用正則表達式分解和轉換IP地址:
下面是利用正則表達式匹配IP地址,并將IP地址轉換成對應數值的javascript程序:
function IP2V(ip) {
re=/(\d+)\.(\d+)\.(\d+)\.(\d+)/g //匹配IP地址的正則表達式
if(re.test(ip)) {
return RegExp.*Math.pow(255,3))+RegExp.*Math.pow(255,2))+RegExp.*255+RegExp.*1
}
else {
throw new Error("Not a valid IP address!")
}
}
不過上面的程序如果不用正則表達式,而直接用split函數來分解可能更簡單,程序如下:
var ip="10.100.20.168"
ip=ip.split(".")
alert("IP值是:"+(ip[0]*255*255*255+ip[1]*255*255+ip[2]*255+ip[3]*1))
匹配Email地址的正則表達式: \w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
匹配網址URL的正則表達式: http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
利用正則表達式去除字串中重復的字符的算法程序:
var s="abacabefgeeii"
var s1=s.replace(/(.).*/g,"")
var re=new RegExp("["+s1+"]","g")
var s2=s.replace(re,"")
alert(s1+s2) //結果為:abcefgi
用正則表達式從URL地址中提取文件名的javascript程序,如下結果為page1
s="http://www.9499.net/page1.htm"
s=s.replace(/(.*\/)([^\.]+).*/ig,"")
alert(s)
利用正則表達式限制網頁表單里的文本框輸入內容:
用正則表達式限制只能輸入中文:
onkeyup="value=value.replace(/[^\u4E00-\u9FA5]/g,'')"
onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\u4E00-\u9FA5]/g,''))"
用正則表達式限制只能輸入全角字符:
onkeyup="value=value.replace(/[^\uFF00-\uFFFF]/g,'')"
onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\uFF00-\uFFFF]/g,''))"
用正則表達式限制只能輸入數字:
onkeyup="value=value.replace(/[^\d]/g,'')
"onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))"
用正則表達式限制只能輸入數字和英文:
onkeyup="value=value.replace(/[\W]/g,'')
"onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))"
文章來源:
http://blog.163.com/ccbobo_cat/blog/static/32099462200961005220547
posted @
2009-07-10 12:52 C.B.K 閱讀(214) |
評論 (0) |
編輯 收藏
ant手冊中的ant配置classpath采用classpath標簽,可是我發現這樣配置總是不好用,還是直接用path可以使用
設置classpath的方法有多種
<path id="project.classpath">
1<pathelement path="${basedir}/lib/aa.jar"/>
2<pathelement location="aa.jar"/>與1的區別在于location可以去當前路徑,當然可以使用絕對路徑
3<filelist id="file" dir="${basedir}/lin">
<file name="a.jar"/>
<file name="d:lib/b.jar"/>
</filelist>
4<fileset dir="d:/lib">
<include name="**/*.jar"/>
</fileset>
5手冊上說了dirset也好用,但是我測試了還是不要用的
</path>
下面說classpath的使用
樣例如下
<javac scdir="./src" destdir="./classes">
<classpath refid="project.classpath"/>
</javac>
下面是比較四種方式的優缺點
第一種調用的需要設置絕對路徑適合第三方jar包
第二種則適合jar包和build.xml文件在同一目錄下的情況,但是我覺得兩個文件放在一起本身就不合理,估計是用的情況不多。
前兩個都是設置單個jar包
第三種是一個文件集合適合引入不同路徑的jar包,但是需要輸入每個jar包的名字,比較繁瑣,適合于jar包屬于不同位置,比較分散但是不多的情況
第四種是一個文件夾,可以采用匹配模式來引入,這個適合在同一個文件夾下,文件名字比較多的情況下
文章來源:
http://blog.163.com/ccbobo_cat/blog/static/32099462200961051533899
posted @
2009-07-10 05:16 C.B.K 閱讀(1648) |
評論 (0) |
編輯 收藏
ant的構建文件中,有很多核心類型,這些核心類型都是XXXSet的形式,主要有以下幾個:PatternSet、DirSet、FileSet、PropertySet、ZipFileSet等。說下前三個的功能就應該可以舉一反三了。
1.PatternSet
即模式集合。顧名思義,就是定義一個模式,他可以用來指定一個文件集合。常常可以被外部的target引用,復用性很強。有includes、
includesfile、excludes、excludesfile屬性。每個屬性里面還可以嵌套name、if、unless等類型。
2.DirSet 即目錄集合。用來定義目錄的集合。有dir、casesensitive、followsymlinks和PatternSet也有的那4個屬性。上面說過PatternSet可以很好的復用。下面就是一個例子:
- <dirset dir="${build.dir}">
- <patternset id="non.test.classes">
- <include name="apps/**/classes"/>
- <exclude name="apps/**/*Test*"/>
- </patternset>
- </dirset>
<dirset dir="${build.dir}">
<patternset id="non.test.classes">
<include name="apps/**/classes"/>
<exclude name="apps/**/*Test*"/>
</patternset>
</dirset>
這是用patternset來定義DirSet的模式,這個模式還可以在外部引用。如:
- <dirset dir="{build.dir}">
- <patternset refid="non.test.classes"/>
- </dirset>
<dirset dir="{build.dir}">
<patternset refid="non.test.classes"/>
</dirset>
上面定義了一個名為non.test.classes的PatternSet,現在就可以引用他了。refid即reference ID.
3.FileSet即文件集合,他的內部屬性與DirSet幾乎一樣,只是多了一個file和defaultexcludes。和dirset一樣,經常
嵌入patternset來定義文件集合;但是也有另外一個很常用的類型,叫selector,它并不是一個真正的類型或元素,只是一種、一類類型的統
稱。如contains、date、depend、depth、different、filename、present、containsregexp、
size、type等。
文章來源:
http://blog.163.com/ccbobo_cat/blog/static/3209946220096105521217
posted @
2009-07-10 05:05 C.B.K 閱讀(429) |
評論 (0) |
編輯 收藏
第一種方法:
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
-> ON <dbname>.*
-> TO <username>@<host name>
-> IDENTIFIED BY '<password>';
where <dbname> is the name of the database you are tyring to
connect to, <username> is the username of the user trying to
connect to the database, <host name> the name of the host (in
your case the XXX host) and <password> the password of the user.
第二種方法:
通過客戶端軟件設置用戶的主機以及權限,


文章來源:
http://blog.163.com/ccbobo_cat/blog/static/32099462200952925050579
posted @
2009-06-29 14:51 C.B.K 閱讀(1563) |
評論 (0) |
編輯 收藏