HttpClient的撑持在HTTP/1.1标准中界说的一切的HTTP办法:GET, HEAD, POST, PUT, DELETE, TRACE 和 OPTIONS。每有一个办法都有一个对应的类:HttpGet,HttpHead,HttpPost,HttpPut,HttpDelete,HttpTrace和HttpOptions。一切的这些类均完成了HttpUriRequest接口,故可以作为execute的履行参数运用。恳求URI是可以使用恳求的一致资本标识符。 HTTP恳求的URI包括一个协议方案protocol scheme,主机名host name,,可选的端口optional port,资本的路径resource path,可选的查询optional query和可选的片段optional fragment。
head,put,delete,trace HttpClient撑持这些办法,
大多数浏览器不撑持这些办法,原因是Html 4中对 FORM 的method办法只撑持两个get和post,很多浏览器还都依然是基于html4的。
通常会在JAVA中经过代码调用URL进行远端办法调用,这些办法有的是Get恳求方法的,有的是POST恳求方法的,为此,总结一例,贴出以便查阅。
依靠JAR包如下图:
?
示例代码:
Java代码 保藏代码
package com.wujintao.httpclient;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.junit.Test;
public class TestCase {
@Test
public void testGetRequest() throws IllegalStateException, IOException {
HttpClient client = new HttpClient();
StringBuilder sb = new StringBuilder();
InputStream ins = null;
// Create a method instance.
GetMethod method = new GetMethod("http://www.baidu.com");
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
System.out.println(statusCode);
if (statusCode == HttpStatus.SC_OK) {
ins = method.getResponseBodyAsStream();
byte[] b = new byte[1024];
int r_len = 0;
while ((r_len = ins.read(b)) > 0) {
sb.append(new String(b, 0, r_len, method
.getResponseCharSet()));
}
} else {
System.err.println("Response Code: " + statusCode);
}
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
} finally {
method.releaseConnection();
if (ins != null) {
ins.close();
}
}
System.out.println(sb.toString());
}
@Test
public void testPostRequest() throws HttpException, IOException {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("http://www.baidu.com/getValue");
method.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded;charset=gb2312");
NameValuePair[] param = { new NameValuePair("age", "11"),
new NameValuePair("name", "jay"), };
method.setRequestBody(param);
int statusCode = client.executeMethod(method);
System.out.println(statusCode);
method.releaseConnection();
}
}
package com.tw.url.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
/**
*
* HTTP公用类
* 所需包:Commons-httpclient.jar,commons-codec-1.3.jar
* 学习拜见网址: https://www.ibm.com/developerworks/cn/opensource/os-cn-crawler/
*
*
* @author tw 2009-07-16
*
*/
public class HttpClientUtils {
public static void main(String arg[]) throws Exception {
String url = "https://www.99bill.com/webapp/receiveDrawbackAction.do" ;
//getDoGetURL2(url,"utf-8");//测验ok
//getDoGetURL(url,"utf-8");//测验ok
getDoPostResponseDataByURL(url, null , "utf-8" , true ); //测验ok
}
/**
*
httpClient的get恳求办法
* @param url = "https://www.99bill.com/webapp/receiveDrawbackAction.do";
* @param charset = ="utf-8";
* @return
* @throws Exception
*/
public static String getDoGetURL(String url, String charset) throws Exception {
HttpClient client = new HttpClient();
GetMethod method1 = new GetMethod(url);
if ( null == url || !url.startsWith( "http" )) {
throw new Exception( "恳求地址格局不对" );
}
// 设置恳求的编码办法
if ( null != charset) {
method1.addRequestHeader( "Content-Type" ,
"application/x-www-form-urlencoded; charset=" + charset);
} else {
method1.addRequestHeader( "Content-Type" ,
"application/x-www-form-urlencoded; charset=" + "utf-8" );
}
int statusCode = client.executeMethod(method1);
if (statusCode != HttpStatus.SC_OK) { // 打印服务器回来的状况
System.out.println( "Method failed: " + method1.getStatusLine());
}
// 回来呼应音讯
byte [] responseBody = method1.getResponseBodyAsString().getBytes(method1.getResponseCharSet());
// 在回来呼应音讯运用编码(utf-8或gb2312)
String response = new String(responseBody, "utf-8" );
System.out.println( "------------------response:" +response);
// 开释衔接
method1.releaseConnection();
return response;
}
/**
*
httpClient的get恳求办法2
* @param url = "http://www.fanselang.com","plus");
* @param url = "http://www.haomad.com","plus");
* @param url = "http://www.metabase.cn","plus");
* @param url = "http://www.3h5.cn","plus");
* @param url = "http://www.4lunwen.cn","plus");
* @param url = "http://www.zx1234.cn","plus");
* @param url = "http://www.majiangji168.cn","plus");
* @param url = "http://www.penbar.cn","plus");
* @param url = "http://www.whathappy.cn","plus");
* @param url = "http://www.lunjin.net","plus");
* @param url = "http://www.ssstyle.cn","plus");
* @param url = "http://www.91fish.cn","plus");
* @param charset = ="utf-8";
* @return
* @throws Exception
*/
public static String getDoGetURL2(String url, String charset)
throws Exception {
/*
* 运用 GetMethod 来拜访一个 URL 对应的页面,完成过程:
* 1:生成一个 HttpClinet 目标并设置相应的参数。
* 2:生成一个 GetMethod 目标并设置呼应的参数。
* 3:用 HttpClinet 生成的目标来履行 GetMethod 生成的Get 办法。
* 4:处置呼应状况码。
* 5:若呼应正常,处置 HTTP 呼应内容。
* 6:开释衔接。
*/
/* 1 生成 HttpClinet 目标并设置参数 */
HttpClient httpClient = new HttpClient();
// 设置 Http 衔接超时为5秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout( 5000 );
/* 2 生成 GetMethod 目标并设置参数 */
GetMethod getMethod = new GetMethod(url);
// 设置 get 恳求超时为 5 秒
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000 );
// 设置恳求重试处置,用的是默许的重试处置:恳求三次
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
String response = "" ;
/* 3 履行 HTTP GET 恳求 */
try {
int statusCode = httpClient.executeMethod(getMethod);
/* 4 判别拜访的状况码 */
if (statusCode != HttpStatus.SC_OK) {
System.err.println( "Method failed: " + getMethod.getStatusLine());
}
/* 5 处置 HTTP 呼应内容 */
// HTTP呼应头部信息,这儿简略打印
Header[] headers = getMethod.getResponseHeaders();
for (Header h : headers)
System.out.println(h.getName() + "------------ " + h.getValue());
// 读取 HTTP 呼应内容,这儿简略打印页面内容
byte [] responseBody = getMethod.getResponseBody(); // 读取为字节数组
response = new String(responseBody, charset);
System.out.println( "----------response:" +response);
// 读取为 InputStream,在页面内容数据量大时分引荐运用
//InputStream response = getMethod.getResponseBodyAsStream();
} catch (HttpException e) {
// 发作丧命的反常,可能是协议不对或许回来的内容有疑问
System.out.println( "Please check your provided http address!" );
e.printStackTrace();
} catch (IOException e) {
// 发作网络反常
e.printStackTrace();
} finally {
/* 6 .开释衔接 */
getMethod.releaseConnection();
}
return response;
}
/**
*
履行一个HTTP POST恳求,回来恳求呼应的HTML
*
* @param url 恳求的URL地址
* @param params 恳求的查询参数,可以为null
* @param charset 字符集
* @param pretty 是否美化
* @return 回来恳求呼应的HTML
*/
public static String getDoPostResponseDataByURL(String url,
Map<string, string=""> params, String charset, boolean pretty) {
StringBuffer response = new StringBuffer();
HttpClient client = new HttpClient();
HttpMethod method = new PostMethod(url);
//设置Http Post数据
if (params != null ) {
HttpMethodParams p = new HttpMethodParams();
for (Map.Entry<string, string=""> entry : params.entrySet()) {
p.setParameter(entry.getKey(), entry.getValue());
}
method.setParams(p);
}
try {
client.executeMethod(method);
if (method.getStatusCode() == HttpStatus.SC_OK) {
//读取为 InputStream,在页面内容数据量大时分引荐运用
BufferedReader reader = new BufferedReader(
new InputStreamReader(method.getResponseBodyAsStream(),
charset));
String line;
while ((line = reader.readLine()) != null ) {
if (pretty)
response.append(line).append(System.getProperty( "line.separator" ));
else
response.append(line);
}
reader.close();
}
} catch (IOException e) {
System.out.println( "履行HTTP Post恳求" + url + "时,发作反常!" );
e.printStackTrace();
} finally {
method.releaseConnection();
}
System.out.println( "--------------------" +response.toString());
return response.toString();
}
}
HttpClient的Get和Post示例,布布扣,bubuko.com
原文地址:http://www.cnblogs.com/haomad/p/3841732.html