歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android入門:發送HTTP的GET和POST請求

Android入門:發送HTTP的GET和POST請求

日期:2017/3/1 10:15:56   编辑:Linux編程

HTTP的請求詳解在《Web資源訪問及HTTP協議詳解》中已經講解過: http://www.linuxidc.com/Linux/2012-07/66007.htm

相關閱讀:Android入門:用HttpClient模擬HTTP的GET和POST請求 http://www.linuxidc.com/Linux/2012-07/66008.htm

一、核心代碼
HTTP GET 核心代碼:
(1)String value = URLEncoder.encode(String value,"UTF-8");
(2)String path = "http://../path?key="+value;
(3)URL url = new URL(path);//此處的URL需要進行URL編碼;
(4)HttpURLConnection con = (HttpURLConnection)url.openConnection();
(5)con.setRequestMethod("GET");
(6)con.setDoOutput(true);
(7)OutputStream out = con.getOutputStream();
(8)out.write(byte[]buf);
(9)int code = con.getResponseCode();
HTTP POST 核心代碼:
(1)String value = URLEncoder.encode(String value,"UTF-8");
(2)byte[]buf = ("key="+value).getBytes("UTF-8");
(3)String path = "http://../path";
(4)URL url = new URL(path);//此處的URL需要進行URL編碼;
(5)HttpURLConnection con = (HttpURLConnection)url.openConnection();
(6)con.setRequestMethod("POST");
(7)con.setDoOutput(true);
(8)OutputStream out = con.getOutputStream();
(9)out.write(byte[]buf);
(10)int code = con.getResponseCode();

二、GET和POST亂碼解決方式
GET:
在doGet中加入:
String name = new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8");
POST:
在doPost中加入:
request.setCharacterEncoding("UTF-8");
詳情請看我的博文:http://www.linuxidc.com/Linux/2012-01/52742.htm

三、服務器端代碼

  1. package org.xiazdong.servlet;
  2. import java.io.IOException;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.annotation.WebServlet;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. @WebServlet("/PrintServlet")
  9. public class PrintServlet extends HttpServlet {
  10. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  11. String name = new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8");
  12. String age = new String(request.getParameter("age").getBytes("ISO-8859-1"),"UTF-8");
  13. System.out.println("姓名:"+name+"\n年齡:"+age);
  14. }
  15. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  16. request.setCharacterEncoding("UTF-8");
  17. System.out.println("姓名:"+request.getParameter("name")+"\n年齡:"+request.getParameter("age"));
  18. }
  19. }

Copyright © Linux教程網 All Rights Reserved