Android入门:发送HTTP的GET和POST请求
Android入门:发送HTTP的GET和POST请求
HTTP的请求详解在《Web资源访问及HTTP协议详解》中已经讲解过:
相关阅读:Android入门:用HttpClient模拟HTTP的GET和POST请求
一、核心代码
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");
详情请看我的博文:
三、服务器端代码
- package org.xiazdong.servlet;
- import java.io.IOException;
- import javax.servlet.ServletException;
- import javax.servlet.annotation.WebServlet;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- @WebServlet("/PrintServlet")
- public class PrintServlet extends HttpServlet {
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- String name = new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8");
- String age = new String(request.getParameter("age").getBytes("ISO-8859-1"),"UTF-8");
- System.out.println("姓名:"+name+"\n年龄:"+age);
- }
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- request.setCharacterEncoding("UTF-8");
- System.out.println("姓名:"+request.getParameter("name")+"\n年龄:"+request.getParameter("age"));
- }
- }
|
评论暂时关闭