HttpClient3.x之Get请求和Post请求示例
最后更新于:2022-04-01 22:59:37
版权声明:本文为博主原创文章,未经博主允许不得转载。如需转载请声明:【转自 http://blog.csdn.net/xiaoxian8023 】
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包有:commons-codec.jar,commons-httpclient.jar,commons-logging.jar。
~~~
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();
}
}
~~~
';