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

來源:互聯網
上載者:User

標籤:

HTTP的請求詳解在我的部落格中已經講解過:

http://blog.csdn.net/xiazdong/article/details/7215296

 

我在http://blog.csdn.net/xiazdong/article/details/7725867 中已經封裝了一個HTTP請求的輔助類,因此可以很簡單的發送GET、POST請求;

如HttpRequestUtil.sendGetRequest();是發送GET請求;

 

 

一、核心代碼  

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://blog.csdn.net/xiazdong/article/details/7217022

 

三、伺服器端代碼  

 

[java] view plain copy 
  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. }  


 

 

四、Android端代碼

 

在AndroidManifest.xml加入:

 

[html] view plain copy 
  1. <uses-permission android:name="android.permission.INTERNET"/>  


MainActivity.java

 

 

[java] view plain copy 
  1. package org.xiazdong.network.submit;  
  2.   
  3. import java.io.OutputStream;  
  4. import java.net.HttpURLConnection;  
  5. import java.net.URL;  
  6. import java.net.URLEncoder;  
  7.   
  8. import android.app.Activity;  
  9. import android.os.Bundle;  
  10. import android.view.View;  
  11. import android.view.View.OnClickListener;  
  12. import android.widget.Button;  
  13. import android.widget.EditText;  
  14. import android.widget.Toast;  
  15.   
  16. public class MainActivity extends Activity {  
  17.     private EditText name, age;  
  18.     private Button getbutton, postbutton;  
  19.     private OnClickListener listener = new OnClickListener() {  
  20.         @Override  
  21.         public void onClick(View v) {  
  22.             try{  
  23.                 if (getbutton == v) {  
  24.                     /* 
  25.                      * 因為是GET請求,所以需要將請求參數添加到URL後,並且還需要進行URL編碼 
  26.                      * URL = http://192.168.0.103:8080/Server/PrintServlet?name=%E6%88%91&age=20 
  27.                      * 此處需要進行URL編碼因為瀏覽器提交時自動進行URL編碼 
  28.                      * */  
  29.                     StringBuilder buf = new StringBuilder("http://192.168.0.103:8080/Server/PrintServlet");  
  30.                     buf.append("?");  
  31.                     buf.append("name="+URLEncoder.encode(name.getText().toString(),"UTF-8")+"&");  
  32.                     buf.append("age="+URLEncoder.encode(age.getText().toString(),"UTF-8"));  
  33.                     URL url = new URL(buf.toString());  
  34.                     HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  35.                     conn.setRequestMethod("GET");  
  36.                     if(conn.getResponseCode()==200){  
  37.                         Toast.makeText(MainActivity.this, "GET提交成功", Toast.LENGTH_SHORT).show();  
  38.                     }  
  39.                     else Toast.makeText(MainActivity.this, "GET提交失敗", Toast.LENGTH_SHORT).show();  
  40.                 }  
  41.                 if (postbutton == v) {  
  42.                     /* 
  43.                      * 如果是POST請求,則請求參數放在請求體中, 
  44.                      * name=%E6%88%91&age=12 
  45.                      *  
  46.                      * */  
  47.                     StringBuilder buf = new StringBuilder();  
  48.                     buf.append("name="+URLEncoder.encode(name.getText().toString(),"UTF-8")+"&");  
  49.                     buf.append("age="+URLEncoder.encode(age.getText().toString(),"UTF-8"));  
  50.                     byte[]data = buf.toString().getBytes("UTF-8");  
  51.                     URL url = new URL("http://192.168.0.103:8080/Server/PrintServlet");  
  52.                     HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  53.                     conn.setRequestMethod("POST");  
  54.                     conn.setDoOutput(true); //如果要輸出,則必須加上此句  
  55.                     OutputStream out = conn.getOutputStream();  
  56.                     out.write(data);  
  57.                     if(conn.getResponseCode()==200){  
  58.                         Toast.makeText(MainActivity.this, "GET提交成功", Toast.LENGTH_SHORT).show();  
  59.                     }  
  60.                     else Toast.makeText(MainActivity.this, "GET提交失敗", Toast.LENGTH_SHORT).show();  
  61.                 }  
  62.             }  
  63.             catch(Exception e){  
  64.                   
  65.             }  
  66.         }  
  67.     };  
  68.   
  69.     @Override  
  70.     public void onCreate(Bundle savedInstanceState) {  
  71.         super.onCreate(savedInstanceState);  
  72.         setContentView(R.layout.main);  
  73.         name = (EditText) this.findViewById(R.id.name);  
  74.         age = (EditText) this.findViewById(R.id.age);  
  75.         getbutton = (Button) this.findViewById(R.id.getbutton);  
  76.         postbutton = (Button) this.findViewById(R.id.postbutton);  
  77.         getbutton.setOnClickListener(listener);  
  78.         postbutton.setOnClickListener(listener);  
  79.     }  
  80. }  


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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.