你好,游客 登录 注册 搜索
背景:
阅读新闻

Android入门:发送HTTP的GET和POST请求

[日期:2012-07-22] 来源:Linux社区  作者:xiazdong [字体:大 中 小]

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

linux
相关资讯       Android入门教程 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款