android中Post方式發送HTTP請求

來源:互聯網
上載者:User

標籤:

Post方式比Get方式要複雜一點,因為該方式需要將請求的參數放在http請求的本文中,所以需要構造請求體。

步驟:

1.構造URL

URL url = new URL(PATH);2.設定串連
HttpURLConnection connection = (HttpURLConnection) url.openConnection();      connection.setConnectTimeout(3000);      connection.setDoInput(true);//表示從伺服器擷取資料      connection.setDoOutput(true);//表示向伺服器寫資料      //獲得上傳資訊的位元組大小以及長度           connection.setRequestMethod("POST");      //是否使用緩衝      connection.setUseCaches(false);      //表示佈建要求體的類型是文本類型      connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");            connection.setRequestProperty("Content-Length", String.valueOf(mydata.length));      connection.connect();   

  3.寫入請求本文

Map<String, String> params = new HashMap<String, String>();params.put("username", "lili");params.put("password", "123");StringBuffer buffer = new StringBuffer();try {//把請求的主體寫入本文!! if(params != null&&!params.isEmpty()){//迭代器  for(Map.Entry<String, String> entry : params.entrySet()){  buffer.append(entry.getKey()).append("=").  append(URLEncoder.encode(entry.getValue(),encode)).  append("&");  }}//   System.out.println(buffer.toString());  //刪除最後一個字元&,多了一個;主體設定完畢  buffer.deleteCharAt(buffer.length()-1);  byte[] mydata = buffer.toString().getBytes(); //獲得輸出資料流,向伺服器輸出資料      OutputStream outputStream = connection.getOutputStream();           outputStream.write(mydata,0,mydata.length);

  4.讀取返回資料,關閉串連

//通常叫做記憶體流,寫在記憶體中的ByteArrayOutputStream outputStream = new ByteArrayOutputStream();byte[] data = new byte[1024];int len = 0;String result = "";if(inputStream != null){try {while((len = inputStream.read(data))!=-1){data.toString();outputStream.write(data, 0, len);}//result是在伺服器端設定的doPost函數中的result = new String(outputStream.toByteArray(),encode);outputStream.flush();

  下面上代碼:一個簡單的Demo訪問一個自建的Servlet:

package com.http.post;    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.MalformedURLException;  import java.net.URL;  import java.net.URLEncoder;  import java.util.HashMap;  import java.util.Map;    public class HttpUtils {        private static String PATH = "http://172.24.87.47:8088/myhttp/servlet/LoginAction";      private static URL url;      public HttpUtils() {          // TODO Auto-generated constructor stub      }        static{          try {              url = new URL(PATH);          } catch (MalformedURLException e) {              // TODO Auto-generated catch block              e.printStackTrace();          }      }      /**      * @param params 填寫的url的參數      * @param encode 位元組編碼      * @return      */      public static String sendPostMessage(Map<String, String> params,String encode){          StringBuffer buffer = new StringBuffer();          try {//把請求的主體寫入本文!!               if(params != null&&!params.isEmpty()){                  //迭代器                for(Map.Entry<String, String> entry : params.entrySet()){                    buffer.append(entry.getKey()).append("=").                    append(URLEncoder.encode(entry.getValue(),encode)).                    append("&");                }              }  //            System.out.println(buffer.toString());                //刪除最後一個字元&,多了一個;主體設定完畢                buffer.deleteCharAt(buffer.length()-1);                byte[] mydata = buffer.toString().getBytes();                 HttpURLConnection connection = (HttpURLConnection) url.openConnection();                connection.setConnectTimeout(3000);                connection.setDoInput(true);//表示從伺服器擷取資料                connection.setDoOutput(true);//表示向伺服器寫資料                //獲得上傳資訊的位元組大小以及長度                               connection.setRequestMethod("POST");                //是否使用緩衝                connection.setUseCaches(false);                //表示佈建要求體的類型是文本類型                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");                                connection.setRequestProperty("Content-Length", String.valueOf(mydata.length));                connection.connect();   //串連,不寫也可以。。??有待瞭解                             //獲得輸出資料流,向伺服器輸出資料                OutputStream outputStream = connection.getOutputStream();                     outputStream.write(mydata,0,mydata.length);                     //獲得伺服器響應的結果和狀態代碼                int responseCode = connection.getResponseCode();                 if(responseCode == HttpURLConnection.HTTP_OK){                   return changeInputeStream(connection.getInputStream(),encode);                                    }          } catch (UnsupportedEncodingException e) {              // TODO Auto-generated catch block              e.printStackTrace();          } catch (IOException e) {              // TODO Auto-generated catch block              e.printStackTrace();          }                    return "";      }     /**     * 將一個輸入資料流轉換成字串     * @param inputStream     * @param encode     * @return     */      private static String changeInputeStream(InputStream inputStream,String encode) {          //通常叫做記憶體流,寫在記憶體中的          ByteArrayOutputStream outputStream = new ByteArrayOutputStream();          byte[] data = new byte[1024];          int len = 0;          String result = "";          if(inputStream != null){              try {                  while((len = inputStream.read(data))!=-1){                      data.toString();                                            outputStream.write(data, 0, len);                  }                  //result是在伺服器端設定的doPost函數中的                  result = new String(outputStream.toByteArray(),encode);                  outputStream.flush();              } catch (IOException e) {                  // TODO Auto-generated catch block                  e.printStackTrace();              }          }          return result;      }        public static void main(String[] arsg){          Map<String, String> params = new HashMap<String, String>();          params.put("username", "lili");          params.put("password", "123");          String result = sendPostMessage(params,"utf-8");          System.out.println("result->"+result);      }  }  

  下邊是服務端的Servlet代碼:

package com.login.manager;    import java.io.ByteArrayOutputStream;  import java.io.IOException;  import java.io.InputStream;  import java.io.InputStreamReader;  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      }        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");          PrintWriter out = response.getWriter();          String username = request.getParameter("username");  //傳過來的內容是:password=123&username=lili        System.out.println("username:"+username);          String pswd = request.getParameter("password");          System.out.println("password:"+pswd);          if(username.equals("張三")&&pswd.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      }    }  

  服務端代碼使用servlet搭建的。。。

這是運行結果:

服務端的:

 在服務端接收的內容是:password=123&username=lili  被它解析啦。。

 

 

android中Post方式發送HTTP請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.