本文:目的和前一篇一样,唯一区别是本文用apache标准接口进行http的post提交数据,而前一篇是用 java标准接口实现。
---------------------------------------------------------------------------------------------------------------------
重点:
1. public static String sendHttpClientPost(String path, Map
内部用apache接口实现http的post提交数据。
2. public static String changeInputStream(InputStream inputStream, String encode)
实现 将一个输入流转变成一个字符串,用指定编码。
---------------------------------------------------------------------------------------------------------------------
注意点:
一.用apache标准接口实现http 的Post提交数据的 关键步骤?
1. 将参数封装到表单请求体中。
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);
2. 使用post方式提交数据
HttpPost httpPost = new HttpPost(path);
httpPost.setEntity(entity);
3. 执行post请求,并获取服务器端的响应HttpResponse
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse httpResponse = client.execute(httpPost);
4. 获取服务器端返回的状态码和输入流,将输入流转换成字符串
if (httpResponse.getStatusLine().getStatusCode() == 200) {
InputStream inputStream = httpResponse.getEntity().getContent();
return changeInputStream(inputStream, encode);
}
二. 编写次程序,要将http协议包添加到 build path , http 协议包在我的资源中。
------------------------------------------------------------------------------------------------------------------------
程序运行结果图:
1. 客户端结果图
2. 服务器端结果图
关键代码:
1. 客户端 HttpUtil.java
package com.httpclient.post;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class HttpUtils {
public HttpUtils() {
// TODO Auto-generated constructor stub
}
//用apache接口实现http的post提交数据
public static String sendHttpClientPost(String path,
Map params, String encode) {
List list = new ArrayList();
if (params != null && !params.isEmpty()) {
for (Map.Entry entry : params.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry
.getValue()));
}
}
try {
// 实现将请求的参数封装到表单中,即请求体中
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);
// 使用post方式提交数据
HttpPost httpPost = new HttpPost(path);
httpPost.setEntity(entity);
// 执行post请求,并获取服务器端的响应HttpResponse
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse httpResponse = client.execute(httpPost);
//获取服务器端返回的状态码和输入流,将输入流转换成字符串
if (httpResponse.getStatusLine().getStatusCode() == 200) {
InputStream inputStream = httpResponse.getEntity().getContent();
return changeInputStream(inputStream, encode);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
/*
* // 把从输入流InputStream按指定编码格式encode变成字符串String
*/
public static String changeInputStream(InputStream inputStream,
String encode) {
// ByteArrayOutputStream 一般叫做内存流
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
String result = "";
if (inputStream != null) {
try {
while ((len = inputStream.read(data)) != -1) {
byteArrayOutputStream.write(data, 0, len);
}
result = new String(byteArrayOutputStream.toByteArray(), encode);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return result;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String path = "http://192.168.0.100:8080/myhttp/servlet/LoginAction";
Map params = new HashMap();
params.put("username", "admin");
params.put("password", "123");
String result = sendHttpClientPost(path, params, "utf-8");
System.out.println("-result->>" + result);
}
}
2. 服务器端servlet LoginAction.java
package com.login.manager;
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 LoginAction extends HttpServlet {
/**
* Constructor of the object.
*/
public LoginAction() {
super();
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//客户端 HttpUtils并没有写request方法是post ,但服务器端可自动识别
String method = request.getMethod();
System.out.println("request method :"+method);
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
System.out.println("-username->>"+username);
String password = request.getParameter("password");
System.out.println("-password->>"+password);
if (username.equals("admin") && password.equals("123")) {
// 表示服务器段返回的结果
out.print("login is success !");
} else {
out.print("login is fail !");
}
out.flush();
out.close();
}
/**
* Initialization of the servlet.
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}