您的位置:首页 > 理论基础 > 计算机网络

一个HttpClient的试验

2007-12-05 18:17 197 查看
其中客户端类:
import java.io.IOException;

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.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class TestClient {

public static void main(String args[]) throws IOException{
TestClient.doGet();
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
TestClient.doPost();
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
TestClient.doDelete();
}
/**
* Get获取
* SongWei
*/
public static void doGet(){
String url = "http://localhost:8080/FrameProject/ReturnMessage";
//构造HttpClient的实例
HttpClient httpClient = new HttpClient();
//创建GET方法的实例
GetMethod getMethod = new GetMethod(url);
//使用系统提供的默认的恢复策略
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
try {
//执行getMethod
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: "
+ getMethod.getStatusLine());
}
//读取内容
byte[] responseBody = getMethod.getResponseBody();
//处理内容
System.out.println(new String(responseBody,"UTF-8"));
} catch (HttpException e) {
//发生致命的异常,可能是协议不对或者返回的内容有问题
System.out.println("Please check your provided http address!");
e.printStackTrace();
} catch (IOException e) {
//发生网络异常
e.printStackTrace();
} finally {
//释放连接
getMethod.releaseConnection();
}
}
/**
* Post获取
* SongWei
*/
public static void doPost() throws IOException{
String url = "http://localhost:8080/FrameProject/ReturnMessage";
// url="http://www.newsmth.net/bbslogin2.php";
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(url);
// 填入各个表单域的值
NameValuePair[] data = { new NameValuePair("id", "youUserName"),
new NameValuePair("passwd", "yourPwd") };
// 将表单的值放入postMethod中
postMethod.setRequestBody(data);
// 执行postMethod
int statusCode = httpClient.executeMethod(postMethod);
System.out.println(statusCode);
//读取内容
byte[] responseBody = postMethod.getResponseBody();
//处理内容
System.out.println(new String(responseBody,"UTF-8"));
// 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.");
}
return;
}else{
System.out.println("other");
}
}

/**
* Delete获取
* SongWei
*/
public static void doDelete(){
String url = "http://localhost:8080/FrameProject/ReturnMessage";
//构造HttpClient的实例
HttpClient httpClient = new HttpClient();
//创建GET方法的实例
DeleteMethod deleteMethod = new DeleteMethod(url);
//使用系统提供的默认的恢复策略
deleteMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
try {
//执行getMethod
int statusCode = httpClient.executeMethod(deleteMethod);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: "
+ deleteMethod.getStatusLine());
}
//读取内容
byte[] responseBody = deleteMethod.getResponseBody();
//处理内容
System.out.println(new String(responseBody,"UTF-8"));
} catch (HttpException e) {
//发生致命的异常,可能是协议不对或者返回的内容有问题
System.out.println("Please check your provided http address!");
e.printStackTrace();
} catch (IOException e) {
//发生网络异常
e.printStackTrace();
} finally {
//释放连接
deleteMethod.releaseConnection();
}
}



}

其中服务器端类(Servlet):

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class for Servlet: ReturnMessage
*
*/
public class ReturnMessage extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/
public ReturnMessage() {
super();
}

/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.println("Get");
pw.println("for Test Only 中国");
pw.println("code=1");
pw.close();
}

/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.println("Post");
pw.println("中国 河北 廊坊");
pw.println("code=2");
pw.close();
// response.sendRedirect("/login.jsp?err='error message'");
}

/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.println("Delete");
pw.println("中国 河南 郑州");
pw.println("code=3");
pw.close();
// response.sendRedirect("/login.jsp?err='error message'");
}


}

测试结果:
Get
for Test Only 中国
code=1




200
Post
中国 河北 廊坊
code=2

other



Delete
中国 河南 郑州
code=3

感觉这几种调用,都是可以返回response的body的.没有什么本质的区别,在实际应用中呢?是否是把其对应成CRUD.只是业务方面的实现不同吧!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: