Http使用post方式提交資料(使用apache標準介面)
本文:目的和前一篇一樣,唯一區別是本文用apache標準介面進行http的post提交資料,而前一篇是用 java標準介面實現。
---------------------------------------------------------------------------------------------------------------------
重點:
1. public static String sendHttpClientPost(String path, Map<String, String> params, String encode)
內部用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<String, String> params, String encode) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> 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<String, String> params = new HashMap<String, String>();
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. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* 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. <br>
*
* 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. <br>
*
* @throws ServletException
* if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}