通过Post方式传递数据给服务器是Android应用程序中的开发提交数据给服务器的一种主要方式,适用于数据量大、数据类型复杂、数据安全要求比较高的场合。
服务器端代码,该处主要编写doGet方法既可:
package com.wangjialin.internet.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ServletForPOSTMethod")
public class ServletForPOSTMethod extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name= request.getParameter("name");
String age= request.getParameter("age");
System.out.println("name from POST method: " + name );
System.out.println("age from POST method: " + age );
}
}
客户端代码:
业务逻辑代码:
package com.wangjialin.internet.userInformation.service;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class UploadUserInformationByPostService {
public static boolean save(String title, String length) throws Exception{
String path = "http://192.168.1.100:8080/ServerForPOSTMethod/ServletForPOSTMethod";
Map<String, String> params = new HashMap<String, String>();
params.put("name", title);
params.put("age", length);
return sendPOSTRequest(path, params, "UTF-8");
}
/**
* 发送POST请求
* @param path 请求路径
* @param params 请求参数
* @return
*/
private static boolean sendPOSTRequest(String path, Map<String, String> params, String encoding) throws Exception{
// title=liming&length=30
StringBuilder sb = new StringBuilder();
if(params!=null && !params.isEmpty()){
for(Map.Entry<String, String> entry : params.entrySet()){
sb.append(entry.getKey()).append("=");
sb.append(URLEncoder.encode(entry.getValue(), encoding));
sb.append("&");
}
sb.deleteCharAt(sb.length() - 1);
}
byte[] data = sb.toString().getBytes();
HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoOutput(true);//允许对外传输数据
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", data.length+"");
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
if(conn.getResponseCode() == 200){
return true;
}
return false;
}
}