package com.qingyuan.httpclient;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
public class doClient extends HttpServlet {
private static final long serialVersionUID = -3068176268692856007L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
// PrintWriter out = response.getWriter();
this.doPost(request, response);
}
/**
* POST http://localhost:8080/httpclient/doClient HTTP/1.1
User-Agent: Fiddler
Host: localhost:8080
Content-Length: 0
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String url = "/httpclient/setup";
String host = "localhost";
HttpClient httpClient = new HttpClient();
httpClient.getHostConfiguration().setHost(host, 8080, "http");
HttpMethod method = postMethod(url);
httpClient.executeMethod(method);
String responseStr = method.getResponseBodyAsString();
System.out.println(responseStr);
}
/**
* 如果PostMethod提交的是中文字符,需要加上相应的编码格式:
* post.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");
* 如果GetMethod提交的参数有中文字符,需要先转换成utf-8格式:
* URLEncoder.encode("武汉", "utf-8");
*
* @throws Exception
*/
private static HttpMethod postMethod(String url) throws IOException
{
PostMethod post = new PostMethod(url);
post.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");
NameValuePair[] param = {
new NameValuePair("startCity","武汉"),
new NameValuePair("lastCity","南京"),
new NameValuePair("userID",""),
new NameValuePair("theDate","") } ;
post.setRequestBody(param);
post.releaseConnection();
return post;
}
@SuppressWarnings("all")
private static HttpMethod getMethod(String url,String param) throws IOException
{
GetMethod get = new GetMethod(url+"?"+param);
get.releaseConnection();
return get;
}
}
package com.qingyuan.httpclient;
import java.io.IOException;
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.PostMethod;
import org.junit.Test;
/**
* 参考: http://www.open-open.com/lib/view/open1377956762049.html
* HttpClient是一个客户端的HTTP通信实现库。HttpClient的目标是发送和接收HTTP报文
* 1) 创建httpclient 对象
* 2)创建请求方法的实例,并指定请求URL,如果需要发送GET请求,创建HTTPGet请求
* 3)如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)
* 方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)
* 方法来设置请求参数
* 4)调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse
* 5)调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;
* 调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。
* 程序可通过该对象获取服务器的响应内容
* 6)释放连接。无论执行方法是否成功,都必须释放连接
*/
public class HttpClientTest
{
// private final static String URL = "http://www.apache.org/";
private final static String localURL = "http://localhost:8080/httpclient/setup";
/**
* <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>405 Method Not Allowed</title>
</head><body>
<h1>Method Not Allowed</h1>
<p>The requested method POST is not allowed for the URL /.</p>
<address>Apache/2.4.12 (Unix) OpenSSL/1.0.1l Server at www.apache.org Port 80</address>
</body></html>
*/
@Test
public void tesst()
{
/* 创建HttpClient实例 */
HttpClient client = new HttpClient();
// PostMethod postMethod = new PostMethod(URL);
PostMethod postMethod = new PostMethod(localURL);
/* 执行post方法 */
try {
int statusCode = client.executeMethod(postMethod);
if (statusCode != HttpStatus.SC_OK)
{
System.err.println("Method failed: "
+ postMethod.getStatusLine());
}
/* 获得返回的结果 */
byte[] responseBody = postMethod.getResponseBody();
// Jesus, you finally here!!
System.out.println(new String(responseBody));
}
catch (HttpException e)
{
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
}
catch (IOException e)
{
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
}
finally
{
/* Release the connection. */
postMethod.releaseConnection();
}
}
public void runClient()
{
HttpClient httpclient = new HttpClient();
// String url = "http://localhost:8080/setup";
String url = "http://www.baidu.com/";
PostMethod postMethod = new PostMethod(url);
// 填入各个表单域的值
NameValuePair[] data =
{
new NameValuePair("ID", "11"),
new NameValuePair("mtg", "0"),
new NameValuePair("havaCookie", "0"),
new NameValuePair("backID", "30"),
new NameValuePair("psw", "password")
};
// 将表单的值放入postMethod中
postMethod.setRequestBody(data);
// 执行postmethod
int statusCode = 0;
try
{
statusCode = httpclient.executeMethod(postMethod);
}
catch(HttpException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
// httpclient 对于要求接受后继服务的请求,像post和put等不能自动处理转发
// 301 或 302
if (HttpStatus.SC_MOVED_PERMANENTLY == statusCode
|| HttpStatus.SC_MOVED_TEMPORARILY == statusCode)
{
// 从头中取出转向的地址:
Header locationHeader = postMethod.getResponseHeader("location");
String location = null;
if (null != locationHeader)
{
location = locationHeader.getValue();
System.out.print("the page was redirected to:" + location);
}
else
{
System.out.print("location field value is null" );
}
return ;
}
else
{
System.out.println(postMethod.getStatusLine());
String str = "";
try
{
str = postMethod.getResponseBodyAsString();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println(str);
}
// 释放连接资源
postMethod.releaseConnection();
}
}
package com.qingyuan.httpclient;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SetupClient extends HttpServlet {
private static final long serialVersionUID = -2009769640673180581L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=gbk");
PrintWriter out = response.getWriter();
out.write("Jesus, you finally here!!");
}
}
1、 commons-httpclient-3.1-rc1.zip
http://jakarta.apache.org/commons/httpclient/downloads.html
http://hc.apache.org/downloads.cgi
2、commons-codec-1.3.jar
http://jakarta.apache.org/site/downloads/downloads_commons-codec.cgi
http://commons.apache.org/proper/commons-codec/
3、commons-logging-api.jar 在tomcat5.5中的Tomcat 5.5/bin目录下或者 http://jakarta.apache.org/site/downloads/downloads_commons-logging.cgi
4: blog
http://blog.youkuaiyun.com/bhq2010/article/details/9210007
http://www.cnblogs.com/mywebname/articles/2130636.html
http://blog.youkuaiyun.com/wangpeng047/article/details/19624529
myeclipse中将整块的代码/所选中的代码左右移动的快捷键选择你要移动的代码,TAB 右移ctrl+TAB左移
需要你在项目中引用几个jar包的:
jackson-core-asl-1.4.0.jar,
jackson-mapper-asl-1.4.0.jar,
json.jar
json-lib-2.4-jdk15.jar
package com.qingyuan.httpclient;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SetupClient extends HttpServlet {
private static final long serialVersionUID = -2009769640673180581L;
/*
* 但是commons-httpclient是一个遗留版本,官方已经不推荐使用,正确的方法是使用httpclient项目的
* httpcore-x.xxx.jar包中的Header:
* import org.apache.http.Header;发送请求时设置头部:
* HttpClient httpClient = new DefaultHttpClient();
*/
//創建一個httpGet方法
//HttpGet httpGet = new HttpGet("http://www.cnblogs.com/loveyakamoz/archive/2011/07/21/2113252.html");
//設置httpGet的头部參數信息
// httpGet.setHeader("Accept", "Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
// httpGet.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
// httpGet.setHeader("Accept-Encoding", "gzip, deflate");
// httpGet.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
// httpGet.setHeader("Connection", "keep-alive");
// httpGet.setHeader("Cookie", "__utma=226521935.73826752.1323672782.1325068020.1328770420.6;");
// httpGet.setHeader("Host", "www.cnblogs.com");
// httpGet.setHeader("refer", "http://www.baidu.com/s?tn=monline_5_dg&bs=httpclient4+MultiThreadedHttpConnectionManager");
// httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");
/* 收到respose时获取头部信息:
Header headers[] = response.getAllHeaders();
int i = 0;
while (i < headers.length)
{
System.out.println(headers[i].getName() + ": " + headers[i].getValue());
i++;
}
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
this.doPost(request, response);
}
/**
* http 中参数获取与传递:
* HttpGet httpget = new HttpGet(
* "http://www.google.com/search?hl=en&q=httpclient&btnG=Google+Search&aq=f&oq=");
*
* HttpClient提供很多工具方法来简化创建和修改执行URI。
*
* URI也可以编程来拼装:
* URI uri = URIUtils.createURI("http", "www.google.com", -1, "/search",
* "q=httpclient&btnG=Google+Search&aq=f&oq=", null);
* HttpGet httpget = new HttpGet(uri);
* System.out.println(httpget.getURI());
*
* >> http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq=
*
* 查询字符串也可以从独立的参数中来生成:
*
* List<NameValuePair> qparams = new ArrayList<NameValuePair>();
* qparams.add(new BasicNameValuePair("q", "httpclient"));
* qparams.add(new BasicNameValuePair("btnG", "Google Search"));
* qparams.add(new BasicNameValuePair("aq", "f"));
* qparams.add(new BasicNameValuePair("oq", null));
* URI uri = URIUtils.createURI("http", "www.google.com", -1, "/search",
* URLEncodedUtils.format(qparams, "UTF-8"), null);
* HttpGet httpget = new HttpGet(uri);
* System.out.println(httpget.getURI());
*
* >> http://www.google.com/search?q=httpclient&btnG=Google+Search&aq=f&oq=
*
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String city = request.getParameter("startCity");
String city2 = request.getParameter("lastCity");
String userId = request.getParameter("userID");
String theDate = request.getParameter("theDate");
response.setContentType("text/html;charset=gbk");
PrintWriter out = response.getWriter();
out.write(city + city2 + userId + theDate + "Jesus, you finally here!!");
}
}