HttpUrlConnection Post提交数据到服务器、并得到服务器返回的数据

来源:互联网 发布:手机看片下什么软件 编辑:程序博客网 时间:2024/05/16 00:48
  1.   
  2. public class HttpUtils {  
  3.     private static String PATH = "http://bdfngdg:8080/myhttp/servlet/LoginAction"; // 服务端地址  
  4.     private static URL url;  
  5.   
  6.     public HttpUtils() {  
  7.         super();  
  8.     }  
  9.   
  10.     // 静态代码块实例化url  
  11.     static {  
  12.         try {  
  13.             url = new URL(PATH);  
  14.         } catch (MalformedURLException e) {  
  15.             e.printStackTrace();  
  16.         }  
  17.     }  
  18.   
  19.     /**  
  20.      * 发送消息体到服务端  
  21.      *   
  22.      * @param params  
  23.      * @param encode  
  24.      * @return  
  25.      */  
  26.     public static String sendPostMessage(Map<String, String> params,  
  27.             String encode) {  
  28.         StringBuilder stringBuilder = new StringBuilder();  
  29.         if (params != null && !params.isEmpty()) {  
  30.             for (Map.Entry<String, String> entry : params.entrySet()) {  
  31.                 try {  
  32.                     stringBuilder  
  33.                             .append(entry.getKey())  
  34.                             .append("=")  
  35.                             .append(URLEncoder.encode(entry.getValue(), encode))  
  36.                             .append("&");  
  37.                 } catch (UnsupportedEncodingException e) {  
  38.                     e.printStackTrace();  
  39.                 }  
  40.             }  
  41.             stringBuilder.deleteCharAt(stringBuilder.length() - 1);  
  42.             try {  
  43.                 HttpURLConnection urlConnection = (HttpURLConnection) url  
  44.                         .openConnection();  
  45.                 urlConnection.setConnectTimeout(3000);  
  46.                 urlConnection.setRequestMethod("POST"); // 以post请求方式提交  
  47.                 urlConnection.setDoInput(true); // 读取数据  
  48.                 urlConnection.setDoOutput(true); // 向服务器写数据  
  49.                 // 获取上传信息的大小和长度  
  50.                 byte[] myData = stringBuilder.toString().getBytes();  
  51.                 // 设置请求体的类型是文本类型,表示当前提交的是文本数据  
  52.                 urlConnection.setRequestProperty("Content-Type",  
  53.                         "application/x-www-form-urlencoded");  
  54.                 urlConnection.setRequestProperty("Content-Length",  
  55.                         String.valueOf(myData.length));  
  56.                 // 获得输出流,向服务器输出内容  
  57.                 OutputStream outputStream = urlConnection.getOutputStream();  
  58.                 // 写入数据  
  59.                 outputStream.write(myData, 0, myData.length);  
  60.                 outputStream.close();  
  61.                 // 获得服务器响应结果和状态码  
  62.                 int responseCode = urlConnection.getResponseCode();  
  63.                 if (responseCode == 200) {  
  64.                     // 取回响应的结果  
  65.                     return changeInputStream(urlConnection.getInputStream(),  
  66.                             encode);  
  67.                 }  
  68.             } catch (IOException e) {  
  69.                 e.printStackTrace();  
  70.             }  
  71.   
  72.         }  
  73.         return "";  
  74.     }  
  75.   
  76.     /**  
  77.      * 将一个输入流转换成指定编码的字符串  
  78.      *   
  79.      * @param inputStream  
  80.      * @param encode  
  81.      * @return  
  82.      */  
  83.     private static String changeInputStream(InputStream inputStream,  
  84.             String encode) {  
  85.   
  86.         // 内存流  
  87.         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
  88.         byte[] data = new byte[1024];  
  89.         int len = 0;  
  90.         String result = null;  
  91.         if (inputStream != null) {  
  92.             try {  
  93.                 while ((len = inputStream.read(data)) != -1) {  
  94.                     byteArrayOutputStream.write(data, 0, len);  
  95.                 }  
  96.                 result = new String(byteArrayOutputStream.toByteArray(), encode);  
  97.             } catch (IOException e) {  
  98.                 e.printStackTrace();  
  99.             }  
  100.         }  
  101.         return result;  
  102.     }  
  103.   
  104.     /**  
  105.      * @param args  
  106.      */  
  107.     public static void main(String[] args) {  
  108.         Map<String, String> map = new HashMap<String, String>();  
  109.         map.put("username", "admin");  
  110.         map.put("password", "123456");  
  111.         String result = sendPostMessage(map, "UTF-8");  
  112.         System.out.println(">>>" + result);  
  113.     }  
  114.   
  115. }  



我们再创建一个服务端工程,一个web project,这里创建一个myhttp的工程,先给它创建一个servlet,用来接收参数访问。

创建的servlet配置如下:

[html] view plaincopy
  1. <servlet>  
  2.         <description>This is the description of my J2EE component</description>  
  3.         <display-name>This is the display name of my J2EE component</display-name>  
  4.         <servlet-name>LoginAction</servlet-name>  
  5.         <servlet-class>com.login.manager.LoginAction</servlet-class>  
  6.     </servlet>  
  7.   
  8.     <servlet-mapping>  
  9.         <servlet-name>LoginAction</servlet-name>  
  10.         <url-pattern>/servlet/LoginAction</url-pattern>  
  11.     </servlet-mapping>  


建立的LoginAction.java类继承HttpServlet:

[html] view plaincopy
  1. package com.login.manager;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. public class LoginAction extends HttpServlet {  
  12.   
  13.     /**  
  14.      * Constructor of the object.  
  15.      */  
  16.     public LoginAction() {  
  17.         super();  
  18.     }  
  19.   
  20.     /**  
  21.      * Destruction of the servlet. <br>  
  22.      */  
  23.     public void destroy() {  
  24.         super.destroy(); // Just puts "destroy" string in log  
  25.         // Put your code here  
  26.     }  
  27.   
  28.     /**  
  29.      * The doGet method of the servlet. <br>  
  30.      *  
  31.      * This method is called when a form has its tag value method equals to get.  
  32.      *   
  33.      * @param request the request send by the client to the server  
  34.      * @param response the response send by the server to the client  
  35.      * @throws ServletException if an error occurred  
  36.      * @throws IOException if an error occurred  
  37.      */  
  38.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  39.             throws ServletException, IOException {  
  40.             this.doPost(request, response);  
  41.     }  
  42.   
  43.     /**  
  44.      * The doPost method of the servlet. <br>  
  45.      *  
  46.      * This method is called when a form has its tag value method equals to post.  
  47.      *   
  48.      * @param request the request send by the client to the server  
  49.      * @param response the response send by the server to the client  
  50.      * @throws ServletException if an error occurred  
  51.      * @throws IOException if an error occurred  
  52.      */  
  53.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  54.             throws ServletException, IOException {  
  55.   
  56.         response.setContentType("text/html;charset=utf-8");  
  57.         request.setCharacterEncoding("utf-8");  
  58.         response.setCharacterEncoding("utf-8");  
  59.         PrintWriter out = response.getWriter();  
  60.         String userName = request.getParameter("username");  
  61.         String passWord = request.getParameter("password");  
  62.         System.out.println("userName:"+userName);  
  63.         System.out.println("passWord:"+passWord);  
  64.         if(userName.equals("admin") && passWord.equals("123456")){ 
  65.                //返回给android客户端的值就是login successful!
  66.             out.print("login successful!");  
  67.         }else{  
  68.             out.print("login failed");  
  69.         }  
  70.         out.flush();  
  71.         out.close();  
  72.     }  
  73.   
  74.     /**  
  75.      * Initialization of the servlet. <br>  
  76.      *  
  77.      * @throws ServletException if an error occurs  
  78.      */  
  79.     public void init() throws ServletException {  
  80.         // Put your code here  
  81.     }  
  82.   
  83. }  
0 0
原创粉丝点击