无材可去补苍天 2011-12-05
工具类 HttpClientUtil
public class HttpClientUtil {
publicstaticStringsendRequest(URLurl)throwsIOException{
Stringresult="";
try{
PostMethodmethod=newPostMethod(url.toString());
method.addRequestHeader("Cache-Control",
RequestConstants.REQUEST_CACHE_CONTROL);
method.addRequestHeader("SOAPAction",
RequestConstants.REQUEST_SOAP_ACTION);
method.addRequestHeader("Cookie",RequestConstants.REQUEST_COOKIE);
method.addRequestHeader("Host",url.getHost());
method.addRequestHeader("Accept",RequestConstants.REQUEST_ACCEPT);
method.setRequestEntity(null);
HttpClienthttpClient=newHttpClient();
intstatus=httpClient.executeMethod(method);
if(method.getResponseContentLength()<0){
ByteArrayOutputStreambout=newByteArrayOutputStream();
byte[]data=newbyte[8192];
intrsize=0;
inttotalrsize=0;
InputStreamin=method.getResponseBodyAsStream();
do{
rsize=in.read(data);
if(rsize>0){
totalrsize+=rsize;
bout.write(data,0,rsize);
}
}while(rsize>0);
result=newString(bout.toByteArray());
}else{
bytedata[]=method.getResponseBody();
result=newString(data,"utf-8");
}
if(status!=200){
log.info("请求错误:[url:"+url.toString()+",responseCode:"
+status+"]");
returnnull;
}
}catch(Exceptione){
log.info("http请求异常!");
}
returnresult;
}public interface RequestConstants {
publicstaticfinalStringREQUEST_CACHE_CONTROL="no-cache";
publicstaticfinalStringREQUEST_SOAP_ACTION="\"\"";
publicstaticfinalStringREQUEST_COOKIE="JSESSIONID=A09JHGHKHU68624309UTY84932;";
publicstaticfinalStringREQUEST_ACCEPT="application/soap+xml,application/dime,multipart/related,text/*";
}action 类
public String listTicketsByCondition() throws IOException {
Stringurl="http://192.168.3.205:8080/GenLotWBOS/queryTickInf.action";
Stringmessageid=this.getRequest().getParameter("messageid");
Stringcpserial=this.getRequest().getParameter("cpserial");
Stringtacketid=this.getRequest().getParameter("tacketid");
PostHelperp=newPostHelper(url);
if(StringUtils.hasLength(messageid)){
p.addParameter("messageid",messageid);
}
if(StringUtils.hasLength(cpserial)){
p.addParameter("cpserial",cpserial);
}
if(StringUtils.hasLength(tacketid)){
p.addParameter("orderno",tacketid);
}
StringjsonMsg=p.post(url);
this.getResponse().setCharacterEncoding("UTF-8");
this.getResponse().getWriter().write(jsonMsg);
this.getResponse().getWriter().flush();
returnnull;
}创建一个 HttpClient 实例,这个实例需要调用 Dispose 方法释放资源,这里使用了 using 语句。接着调用 GetAsync,给它传递要调用的方法的地址,向服务器发送 Get 请求。