Android入門:用HttpClient類比HTTP的GET和POST請求

來源:互聯網
上載者:User
一、HttpClient介紹HttpClient是用來類比HTTP請求的,其實實質就是把HTTP請求類比後發給Web伺服器;
Android已經整合了HttpClient,因此可以直接使用;
註:此處HttpClient代碼不只可以適用於Android,也可適用於一般的Java程式;
HTTP GET核心代碼:
(1)DefaultHttpClient client = new DefaultHttpClient();(2)HttpGet get = new HttpGet(String url);//此處的URL為http://..../path?arg1=value&....argn=value(3)HttpResponse response = client.execute(get); //類比請求(4)int code = response.getStatusLine().getStatusCode();//返迴響應碼(5)InputStream in = response.getEntity().getContent();//伺服器返回的資料

HTTP POST核心代碼:
(1)DefaultHttpClient client = new DefaultHttpClient();(2)BasicNameValuePair pair = new BasicNameValuePair(String name,String value);//建立一個要求標頭的欄位,比如content-type,text/plain(3)UrlEncodedFormEntity entity = new UrlEncodedFormEntity(List<NameValuePair> list,String encoding);//對自訂要求標頭進行URL編碼(4)HttpPost post = new HttpPost(String url);//此處的URL為http://..../path(5)post.setEntity(entity);(6)HttpResponse response = client.execute(post);(7)int code = response.getStatusLine().getStatusCode();(8)InputStream in = response.getEntity().getContent();//伺服器返回的資料

二、伺服器端代碼
伺服器端代碼和通過URLConnection發出請求的代碼不變:
package org.xiazdong.servlet;import java.io.IOException;import java.io.OutputStream;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("/Servlet1")public class Servlet1 extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String nameParameter = request.getParameter("name");String ageParameter = request.getParameter("age");String name = new String(nameParameter.getBytes("ISO-8859-1"),"UTF-8");String age = new String(ageParameter.getBytes("ISO-8859-1"),"UTF-8");System.out.println("GET");System.out.println("name="+name);System.out.println("age="+age);response.setCharacterEncoding("UTF-8");OutputStream out = response.getOutputStream();//返回資料out.write("GET請求成功!".getBytes("UTF-8"));out.close();}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");String name = request.getParameter("name");String age  = request.getParameter("age");System.out.println("POST");System.out.println("name="+name);System.out.println("age="+age);response.setCharacterEncoding("UTF-8");OutputStream out = response.getOutputStream();out.write("POST請求成功!".getBytes("UTF-8"));out.close();}}
三、Android用戶端代碼
效果如下:



在AndroidManifest.xml加入:

<uses-permission android:name="android.permission.INTERNET"/>  


MainActivity.java

package org.xiazdong.network.httpclient;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.URLEncoder;import java.util.ArrayList;import java.util.List;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.Toast;public class MainActivity extends Activity {private EditText name, age;private Button getbutton, postbutton;private OnClickListener listener = new OnClickListener() {@Overridepublic void onClick(View v) {try{if(postbutton==v){/* * NameValuePair代表一個HEADER,List<NameValuePair>儲存全部的頭欄位 * UrlEncodedFormEntity類似於URLEncoder語句進行URL編碼 * HttpPost類似於HTTP的POST請求 * client.execute()類似於發出請求,並返回Response */DefaultHttpClient client = new DefaultHttpClient();List<NameValuePair> list = new ArrayList<NameValuePair>();NameValuePair pair1 = new BasicNameValuePair("name", name.getText().toString());NameValuePair pair2 = new BasicNameValuePair("age", age.getText().toString());list.add(pair1);list.add(pair2);UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8");HttpPost post = new HttpPost("http://192.168.0.103:8080/Server/Servlet1");post.setEntity(entity);HttpResponse response = client.execute(post);if(response.getStatusLine().getStatusCode()==200){InputStream in = response.getEntity().getContent();//接收伺服器的資料,並在Toast上顯示String str = readString(in);Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();}else Toast.makeText(MainActivity.this, "POST提交失敗", Toast.LENGTH_SHORT).show();}if(getbutton==v){DefaultHttpClient client = new DefaultHttpClient();StringBuilder buf = new StringBuilder("http://192.168.0.103:8080/Server/Servlet1");buf.append("?");buf.append("name="+URLEncoder.encode(name.getText().toString(),"UTF-8")+"&");buf.append("age="+URLEncoder.encode(age.getText().toString(),"UTF-8"));HttpGet get = new HttpGet(buf.toString());HttpResponse response = client.execute(get);if(response.getStatusLine().getStatusCode()==200){InputStream in = response.getEntity().getContent();String str = readString(in);Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();}else Toast.makeText(MainActivity.this, "GET提交失敗", Toast.LENGTH_SHORT).show();}}catch(Exception e){}}};    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);name = (EditText) this.findViewById(R.id.name);age = (EditText) this.findViewById(R.id.age);getbutton = (Button) this.findViewById(R.id.getbutton);postbutton = (Button) this.findViewById(R.id.postbutton);getbutton.setOnClickListener(listener);postbutton.setOnClickListener(listener);    }protected String readString(InputStream in) throws Exception {byte[]data = new byte[1024];int length = 0;ByteArrayOutputStream bout = new ByteArrayOutputStream();while((length=in.read(data))!=-1){bout.write(data,0,length);}return new String(bout.toByteArray(),"UTF-8");}}
相關文章

聯繫我們

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