StringBuildersb=newStringBuilder();
InputStreamins=null;
//Createamethodinstance.
GetMethodmethod=newGetMethod("http://www.baidu.com");
//Providecustomretryhandlerisnecessary
method.getParams().setParameter(HttpMethodParams.RETRY_HA
NDLER,
newDefaultHttpMethodRetryHandler(3,fals
e));
try{
//Executethemethod.
intstatusCode=client.executeMethod(method);
System.out.println(statusCode);
if(statusCode==HttpStatus.SC_OK){
ins=method.getResponseBodyAsStream();
byte[]b=newbyte[1024];
intr_len=0;
while((r_len=ins.read(b))>0){
sb.append(newString(b,0,r_len,
method
.getResponseCharS
et()));
}
}else{
System.err.println("ResponseCode:"+st
atusCode);
}
}catch(HttpExceptione){
System.err.println("Fatalprotocolviolation:"+
e.getMessage());
}catch(IOExceptione){
System.err.println("Fataltransporterror:"+e.
getMessage());
}finally{
method.releaseConnection();
if(ins!=null){
ins.close();
}
}
System.out.println(sb.toString());
}
@Test
publicvoidtestPostRequest()throwsHttpException,IOException{
HttpClientclient=newHttpClient();
PostMethodmethod=newPostMethod("http://www.baidu.com/
getValue");
method.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded;charse
t=gb2312");
NameValuePair[]param={newNameValuePair("age","11"),
newNameValuePair("name","jay"),};
method.setRequestBody(param);
intstatusCode=client.executeMethod(method);
System.out.println(statusCode);
method.releaseConnection();
评论0
最新资源