package CJava;
import java.io.IOException;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
/**
* 本文简单介绍一些httpclient的基本内容,因为在实际开发当中使用到
* 基于http协议,现在网络上基本上是属于比较常用的协议类型,
* HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,
* @author lvzh
*
*/
public class HttpClientTest {
private HttpClient client = new HttpClient();
/**
* 读取页面的内容,不管是http还是https
* 将访问地址
*/
public void getWebPageContent(){
HttpMethod method=new GetMethod("http://www.baidu.com");
try {
client.executeMethod(method);
System.out.println("server status is : "+method.getStatusLine());
System.out.println("content is : "+method.getResponseBodyAsString());
method.releaseConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 得到一个使用post提交的对象
* @return
*/
private static HttpMethod getPostMethod(){
PostMethod post = new PostMethod( "/simcard.php" );
NameValuePair simcard = new NameValuePair( "mob" , "1330227" );
post.setRequestBody( new NameValuePair[] { simcard});
return post;
}
/**
* 返回一个通过GET提交的对象
* @return
*/
public static HttpMethod getGETMethod(){
return new GetMethod("/simcard.php?simcard=1330227");
}
/**
* 像特定页面提交参数
*/
public void sampleOne(){
HttpMethod method = null;
client.getHostConfiguration().setHost( "www.imobile.com.cn" , 80, "http" );
/*使用post方式提交*/
method = getPostMethod();
try {
client.executeMethod(method);
//打印服务器返回的状态
System.out.println(method.getStatusLine()); //打印结果页面
String response=new String(method.getResponseBodyAsString().getBytes("ISO-8859-1"));
//打印返回的信息
System.out.println(response);
method.releaseConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 模拟重定向 simcard.php --重定向到---> www.imobile.com.cn
*/
public void simulateRedirect(){
HttpMethod method = null;
client.getHostConfiguration().setHost( "www.imobile.com.cn" , 80, "http" );
method = getPostMethod();
try{
client.executeMethod(method);
int statuscode = method.getStatusCode();
if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY) || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
// 读取新的 URL 地址
Header header=method.getResponseHeader("location");
if (header!=null){
String newuri=header.getValue();
System.out.println("newuri is:"+newuri);
if((newuri==null)||(newuri.equals("")))
newuri="/";
GetMethod redirect=new GetMethod(newuri);
client.executeMethod(redirect);
System.out.println("Redirect:"+redirect.getStatusLine().toString());
String response=new String(redirect.getResponseBodyAsString().getBytes("gbk"));
//打印返回的信息
System.out.println(response);
redirect.releaseConnection();
}else
System.out.println("Invalid redirect");
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
HttpClientTest client = new HttpClientTest();
client.simulateRedirect();
}
}
HTTPClient 基础使用 一
最新推荐文章于 2023-09-01 09:46:51 发布