ANDROID_MARS学习笔记_S04_004_用HTTPCLENT发带参数的get和post请求

一、代码

1.xml
(1)activity_main.xml

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:paddingBottom="@dimen/activity_vertical_margin"
 6     android:paddingLeft="@dimen/activity_horizontal_margin"
 7     android:paddingRight="@dimen/activity_horizontal_margin"
 8     android:paddingTop="@dimen/activity_vertical_margin"
 9     tools:context="com.http2.MainActivity" >
10 
11     <EditText
12         android:id="@+id/nameText"
13         android:layout_width="wrap_content"
14         android:layout_height="wrap_content"
15         android:text="小明" 
16         />
17     <EditText
18         android:id="@+id/ageText"
19         android:layout_width="wrap_content"
20         android:layout_height="wrap_content"
21         android:text="123" 
22         />
23     <Button
24         android:id="@+id/getBtnId"
25         android:layout_width="wrap_content"
26         android:layout_height="wrap_content"
27         android:text="Get请求" 
28         android:onClick="getHttp"/>
29     <Button
30         android:id="@+id/postBtnId"
31         android:layout_width="wrap_content"
32         android:layout_height="wrap_content"
33         android:text="Post请求" 
34         android:onClick="postHttp"/>
35 
36 </LinearLayout>

(2)AndroidManifest.xml

增加

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

2.java
(1)HandleRequest.java  服务器端Servlet

 1 package servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 public class HandleRequest extends HttpServlet {
12 
13     public void doGet(HttpServletRequest request, HttpServletResponse response)
14             throws ServletException, IOException {
15         System.out.println("doGet");
16         request.setAttribute("method", "get访求访问");
17         request.setAttribute("name", request.getParameter("name"));
18         request.setAttribute("age", request.getParameter("age"));
19         response.getWriter().print("get访求访问--->"+request.getParameter("name")+"--->"+request.getParameter("age"));
20         //request.getRequestDispatcher("index.jsp").forward(request, response);
21     }
22     
23     public void doPost(HttpServletRequest request, HttpServletResponse response)
24             throws ServletException, IOException {
25         System.out.println("doPost");
26         request.setAttribute("method", "post访求访问");
27         request.setAttribute("name", request.getParameter("name"));
28         request.setAttribute("age", request.getParameter("age"));
29         response.getWriter().print("post访求访问--->"+request.getParameter("name")+"--->"+request.getParameter("age"));
30         //request.getRequestDispatcher("index.jsp").forward(request, response);
31     }
32 
33 }

(2)MainActivity.java 

 1 package com.http2;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import android.app.Activity;
 7 import android.os.Bundle;
 8 import android.view.View;
 9 import android.widget.EditText;
10 
11 public class MainActivity extends Activity {
12 
13     //private Button getBtn,postBtn = null;
14     private EditText nameView,ageView = null;
15     private String baseUrl = "http://192.168.1.104:8080/AndroidServerTest/HandleRequest";
16     private String name,age = null;
17     @Override
18     protected void onCreate(Bundle savedInstanceState) {
19         super.onCreate(savedInstanceState);
20         setContentView(R.layout.activity_main);
21         
22         nameView = (EditText) findViewById(R.id.nameText);
23         ageView = (EditText) findViewById(R.id.ageText);
24         name = nameView.getText().toString();
25         age = ageView.getText().toString();
26     }
27     
28     public void getHttp(View view) {
29         String url = baseUrl + "?name=" + name + "&age=" + age;
30         HttpAsyncTask httpAsyncTask = new HttpAsyncTask(url, "get");
31         httpAsyncTask.execute("");
32     }
33     public void postHttp(View view) {
34         //post的参数会放在httpEntity里,所以不用拼url
35         List<String> parmas = new ArrayList<String>();
36         parmas.add(name);
37         parmas.add(age);
38         HttpAsyncTask httpAsyncTask = new HttpAsyncTask(baseUrl, "post", parmas);
39         httpAsyncTask.execute("");
40     }
41     
42 }

(3)HttpAsyncTask.java

  1 package com.http2;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.IOException;
  5 import java.io.InputStream;
  6 import java.io.InputStreamReader;
  7 import java.io.UnsupportedEncodingException;
  8 import java.util.ArrayList;
  9 import java.util.List;
 10 
 11 import org.apache.http.HttpEntity;
 12 import org.apache.http.HttpResponse;
 13 import org.apache.http.NameValuePair;
 14 import org.apache.http.client.ClientProtocolException;
 15 import org.apache.http.client.HttpClient;
 16 import org.apache.http.client.entity.UrlEncodedFormEntity;
 17 import org.apache.http.client.methods.HttpGet;
 18 import org.apache.http.client.methods.HttpPost;
 19 import org.apache.http.client.methods.HttpRequestBase;
 20 import org.apache.http.impl.client.DefaultHttpClient;
 21 import org.apache.http.message.BasicNameValuePair;
 22 
 23 import android.os.AsyncTask;
 24 
 25 public class HttpAsyncTask extends AsyncTask<String, Void, Void> {
 26 
 27     private String url;
 28     private String method;
 29     private List<String> params;
 30     
 31     public HttpAsyncTask(String url, String method) {
 32         super();
 33         this.url = url;
 34         this.method = method;
 35     }
 36     public HttpAsyncTask(String url, String method, List<String> params) {
 37         super();
 38         this.url = url;
 39         this.method = method;
 40         this.params = params;
 41     }
 42 
 43     @Override
 44     protected Void doInBackground(String... params) {
 45         if("get".equals(method))
 46             sendGetHttpRequest(url);
 47         else if("post".equals(method))
 48             sendPostRequest(url, this.params);
 49         return null;
 50     }
 51     
 52     private void sendPostRequest(String url,List<String> params) {
 53         System.out.println("sendPostRequest---->");
 54         NameValuePair nameValuePair1 = new BasicNameValuePair("name", this.params.get(0));
 55         NameValuePair nameValuePair2 = new BasicNameValuePair("age", this.params.get(1));
 56         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
 57         nameValuePairs.add(nameValuePair1);
 58         nameValuePairs.add(nameValuePair2);
 59         InputStream inputStream = null;
 60         try {
 61             //请求体
 62             HttpEntity httpEntity = new UrlEncodedFormEntity(nameValuePairs);
 63             //url不用带参数-->"?a=1&b=2"
 64             HttpPost httpPost = new HttpPost(url);
 65             httpPost.setEntity(httpEntity);
 66             HttpClient httpClient = new DefaultHttpClient();
 67             HttpResponse httpResponse = httpClient.execute(httpPost);
 68             HttpEntity respHttpEntity = httpResponse.getEntity();
 69             inputStream = respHttpEntity.getContent();
 70             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
 71             String line = null;
 72             StringBuilder sb = new StringBuilder();
 73             while ((line = reader.readLine()) != null) {
 74                 sb.append(line);
 75             }
 76             System.out.println(sb);
 77         } catch (Exception e) {
 78             e.printStackTrace();
 79         }
 80     }
 81         
 82     private void sendGetHttpRequest(String url) {
 83         System.out.println("sendGetHttpRequest---->");
 84         //生成一个请求对象
 85         HttpGet httpGet = new HttpGet(url);
 86         //生成一个Http客户端对象
 87         HttpClient httpClient = new DefaultHttpClient();
 88         InputStream inputStream = null;
 89         //使用Http客户端发送请求对象
 90         try {
 91             HttpResponse httpResponse = httpClient.execute(httpGet);
 92             HttpEntity httpEntity = httpResponse.getEntity();
 93             inputStream = httpEntity.getContent();
 94             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
 95             String line = null;
 96             StringBuilder sb = new StringBuilder();
 97             while ((line = reader.readLine()) != null) {
 98                 sb.append(line);
 99             }
100             System.out.println(sb);
101         } catch (ClientProtocolException e) {
102             e.printStackTrace();
103         } catch (IOException e) {
104             e.printStackTrace();
105         } finally {
106             try {
107                 inputStream.close();
108             } catch (IOException e) {
109                 e.printStackTrace();
110             }
111         }
112     }
113 
114 }
原文地址:https://www.cnblogs.com/shamgod/p/5205638.html