一个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.只是业务方面的实现不同吧!
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.只是业务方面的实现不同吧!
相关文章推荐
- java web HttpClient 开发一个接口
- HttpClient例子一个返回html一个返回字符流
- 一个httpclient4实例跨域访问会报错,谁知道在什么情况下会出现这个问题?
- 推荐一个很好的 HttpClient 入门教程
- Android如何构建一个https请求的httpClient
- HttpClient4 Post XML到一个服务器上
- 求救一个关于commons-httpclient组件在网络连接过程中的速度问题,好奇怪啊。。。
- 由RP编程联想到一个Apache Async Http Client的问题
- 如何写一个HttpClient[1]——URI的处理
- HttpClient4 Post XML到一个服务器上
- 一个强大的调远程接口强大工具HttpClient
- 用C语言实现一个简单的HTTP客户端(HTTP Client)
- SuperWebClient -一个基于CURL的.NET HTTP-HTTPS模拟神组件(1)
- 一个c#的与web服务器交互的HttpClient类
- 如何把Volley改成一个爬虫--HttpClient设置
- [置顶] 读《http 权威指南后》,写的一个只有18K 大小的httpClient
- Httpclient4.5.2 POST Json 数据到另外一个网站, 解析
- apache httpclient CacheStorage的一个自定义实现
- golang入门--一个简单的http client
- Http与HttpClient(已被废弃)通信的介绍,附带一个Http发送GET请求工具类的例子