Android学习之Http使用Post方式进行数据提交(普通数据和Json数据)

转自:http://blog.csdn.net/wulianghuan/article/details/8626551

 

我们知道通过Get方式提交的数据是作为Url地址的一部分进行提交,而且对字节数的长度也有限制,与Get方式类似,http-post参数也是被URL编码的,然而它的变量名和变量值不作为URL的一部分被传送,而是放在实际的HTTP请求消息内部被传送。

可以通过如下的代码设置POST提交方式参数:

[html]  view plain copy print ?
 
  1. HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();  
  2. urlConnection.setConnectTimeout(3000);  
  3. urlConnection.setRequestMethod("POST"); //以post请求方式提交  
  4. urlConnection.setDoInput(true);     //读取数据  
  5. urlConnection.setDoOutput(true);    //向服务器写数据  
  6. //获取上传信息的大小和长度  
  7. byte[] myData = stringBuilder.toString().getBytes();  
  8. //设置请求体的类型是文本类型,表示当前提交的是文本数据  
  9. urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
  10. urlConnection.setRequestProperty("Content-Length", String.valueOf(myData.length));  


这里使用一个案例来看一下如何使用post方式提交数据到服务器:

首先我们创建一个java project,只要创建一个类就行,我们创建一个HttpUtils.java类,

【代码如下】:

package com.demo;

import java.net.MalformedURLException;
import java.net.URL;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class HttpUtils {
    private static String PATH = "http://192.168.1.8:8080/demo_server/getjson2.action"; // 服务端地址
    private static URL url;

    public HttpUtils() {
        super();
    }

    // 静态代码块实例化url
    static {
        try {
            url = new URL(PATH);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送消息体到服务端
     * 
     * @param params
     * @param encode
     * @return
     */
    public static String sendPostMessage(Map<String, String> params,
            String encode) {
        StringBuilder stringBuilder = new StringBuilder();
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                try {
                    stringBuilder
                            .append(entry.getKey())
                            .append("=")
                            .append(URLEncoder.encode(entry.getValue(), encode))
                            .append("&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            //删掉最后一个“&”
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            System.out.println(stringBuilder);
            try {
                HttpURLConnection urlConnection = (HttpURLConnection) url
                        .openConnection();
                urlConnection.setConnectTimeout(3000);
                urlConnection.setRequestMethod("POST"); // 以post请求方式提交
                urlConnection.setDoInput(true); // 读取数据
                urlConnection.setDoOutput(true); // 向服务器写数据
                // 获取上传信息的大小和长度
                byte[] myData = stringBuilder.toString().getBytes();
                // 设置请求体的类型是文本类型,表示当前提交的是文本数据
                urlConnection.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
                urlConnection.setRequestProperty("Content-Length",
                        String.valueOf(myData.length));
                // 获得输出流,向服务器输出内容
                OutputStream outputStream = urlConnection.getOutputStream();
                // 写入数据
                outputStream.write(myData, 0, myData.length);
                outputStream.close();
                // 获得服务器响应结果和状态码
                int responseCode = urlConnection.getResponseCode();
                if (responseCode == 200) {
                    // 取回响应的结果
                    return changeInputStream(urlConnection.getInputStream(),
                            encode);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return "";
    }

    /**
     * 将一个输入流转换成指定编码的字符串
     * 
     * @param inputStream
     * @param encode
     * @return
     */
    private static String changeInputStream(InputStream inputStream,
            String encode) {

        // 内存流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
        String result = null;
        if (inputStream != null) {
            try {
                while ((len = inputStream.read(data)) != -1) {
                    byteArrayOutputStream.write(data, 0, len);
                }
                result = new String(byteArrayOutputStream.toByteArray(), encode);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static void main(String args[]){
        List<Music> list = new ArrayList<Music>();
                // JsonArray jsonArray = new JsonArray();
                // JsonObject jsonObject = new JsonObject();
                Gson gson = new Gson();
                Music m1 = new Music();
                m1.setId(1);
                m1.setAuthor("游鸿明");
                m1.setName("白色恋人");
                m1.setTime("04:01");
                list.add(m1);
                Music m2 = new Music();
                m2.setId(2);
                m2.setAuthor("陈奕迅");
                m2.setName("淘汰");
                m2.setTime("04:44");
                list.add(m2);
                Music m3 = new Music();
                m3.setId(3);
                m3.setAuthor("谢霆锋");
                m3.setName("黄种人");
                m3.setTime("04:24");
                list.add(m3);
                java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<Music>>() {
                }.getType();
                String beanListToJson = gson.toJson(list, type);
                System.out.println("GSON-->" + beanListToJson);
                
                Map<String, String> map = new HashMap<String, String>();
                map.put("username", "admin");
                map.put("password", "123456");
                map.put("json", beanListToJson);
                String result = sendPostMessage(map, "UTF-8");
                System.out.println(">>>" + result);
    }

}

 


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

创建的servlet配置如下:

[html]  view plain copy print ?
 
  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 plain copy print ?
 
  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.         String json = request.getParameter("json");
  63.         System.out.println("userName:"+userName);  
  64.         System.out.println("passWord:"+passWord);  
  65.         System.out.println("json:"+json);
  66.         if(userName.equals("admin") && passWord.equals("123456")){  
  67.             out.print("login successful!");  
  68.         }else{  
  69.             out.print("login failed");  
  70.         }  
  71.         out.flush();  
  72.         out.close();  
  73.     }  
  74.   
  75.     /**  
  76.      * Initialization of the servlet. <br>  
  77.      *  
  78.      * @throws ServletException if an error occurs  
  79.      */  
  80.     public void init() throws ServletException {  
  81.         // Put your code here  
  82.     }  
  83.   
  84. }  


 

我们运行java project,控制台输出如下:

>>>login successful!

转载于:https://www.cnblogs.com/x_wukong/p/4300473.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值