JAVA实现httpClient实例
package net.zhutou.http; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; /** * @author 猪头 */ public class MyClient { /** *的到Http请求结果 * @param url请求地址 * @param parms请求参数 * @return */ public byte[] getBody(String url,Map parms){ byte[] body=null; //构造HttpClient的实例 HttpClient httpClient = new HttpClient(); //创建GET方法的实例 PostMethod postMethod = new PostMethod(url); //填入各个表单域的值 NameValuePair[] data = new NameValuePair[parms.keySet().size()]; Iterator it = parms.entrySet().iterator(); int i=0; while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); Object key = entry.getKey(); Object value = entry.getValue(); data[i]=new NameValuePair(key.toString(),value.toString()); i++; } //将表单的值放入postMethod中 postMethod.setRequestBody(data); try { //执行postMethod int statusCode = httpClient.executeMethod(postMethod); // HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发 // 301或者302 if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { //从头中取出转向的地址 Header locationHeader = postMethod .getResponseHeader(“location”); String location = null; if (locationHeader != null) { location = locationHeader.getValue(); System.out .println(“The page was redirected to:” + location); } else { System.err.println(“Location field value is null.”); } } body = postMethod.getResponseBody(); } catch (Exception e) { e.printStackTrace(); } return body; } public static void main(String[] args) { String url=“http://www.huawei.com”; Map parms=new HashMap(); MyClient client=new MyClient(); String result=new String(client.getBody(url, parms)); System.out.println(result); } }
相关推荐
84487600 2020-08-16
似水流年梦 2020-08-09
knightwatch 2020-07-26
fengchao000 2020-06-16
标题无所谓 2020-06-14
sicceer 2020-06-12
yanghui0 2020-06-09
yanghui0 2020-06-09
创建一个 HttpClient 实例,这个实例需要调用 Dispose 方法释放资源,这里使用了 using 语句。接着调用 GetAsync,给它传递要调用的方法的地址,向服务器发送 Get 请求。
wanghongsha 2020-06-04
jiaguoquan00 2020-05-26
zhaolisha 2020-05-16
wanghongsha 2020-05-05
wanghongsha 2020-04-14
knightwatch 2020-04-11
hygbuaa 2020-03-27
zergxixi 2020-03-24