/*
* Created on
* Copyright by All Rights Reserved
*
*/
package netxfokhttp;
import javautilHashMap; import javautilIterator; import javautilMap;
import mons; import mons; import mons; import mons; import mons;
/**
* @author YangHua
*/
public class MyClient {
/**
*的到Http请求结果
* @param url请求地址
* @param parms请求参数
* @return
*/
public byte[] getBody(String urlMap parms){
byte[] body=null;
//构造HttpClient的实例
HttpClient httpClient = new HttpClient();
//创建GET方法的实例
PostMethod postMethod = new PostMethod(url);
//填入各个表单域的值
NameValuePair[] data = new NameValuePair[parmskeySet()size()]; Iterator it = parmsentrySet(erator();
int i=;
while (ithasNext()) { MapEntry entry = (MapEntry) itnext(); Object key = entrygetKey(); Object value = entrygetValue(); data[i]=new NameValuePair(keytoString()valuetoString());
i++;
}
//将表单的值放入postMethod中
postMethodsetRequestBody(data);
try {
//执行postMethod
int statusCode = (postMethod); // HttpClient对于要求接受后继服务的请求象POST和PUT等不能自动处理转发
// 或者
if (statusCode == HttpStatusSC_MOVED_PERMANENTLY || statusCode == HttpStatusSC_MOVED_TEMPORARILY) {
//从头中取出转向的地址
Header locationHeader = postMethod
getResponseHeader(location);
String location = null;
if (locationHeader != null) { location = locationHeadergetValue(); Systemout println(The page was redirected to: + location);
} else {
Systemerrprintln(Location field value is null);
}
}
body = postMethodgetResponseBody();
} catch (Exception e) {
eprintStackTrace();
}
return body;
}
public static void main(String[] args) {
String url=;
Map parms=new HashMap();
MyClient client=new MyClient();
String result=new String(clientgetBody(url parms)); Systemoutprintln(result);
}
}
出处