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

时间:2023-03-10 02:50:19
ANDROID_MARS学习笔记_S04_004_用HTTPCLENT发带参数的get和post请求

一、代码

1.xml
(1)activity_main.xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.http2.MainActivity" > <EditText
android:id="@+id/nameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="小明"
/>
<EditText
android:id="@+id/ageText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="123"
/>
<Button
android:id="@+id/getBtnId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get请求"
android:onClick="getHttp"/>
<Button
android:id="@+id/postBtnId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Post请求"
android:onClick="postHttp"/> </LinearLayout>

(2)AndroidManifest.xml

增加

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

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

 package servlet;

 import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class HandleRequest extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("doGet");
request.setAttribute("method", "get访求访问");
request.setAttribute("name", request.getParameter("name"));
request.setAttribute("age", request.getParameter("age"));
response.getWriter().print("get访求访问--->"+request.getParameter("name")+"--->"+request.getParameter("age"));
//request.getRequestDispatcher("index.jsp").forward(request, response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("doPost");
request.setAttribute("method", "post访求访问");
request.setAttribute("name", request.getParameter("name"));
request.setAttribute("age", request.getParameter("age"));
response.getWriter().print("post访求访问--->"+request.getParameter("name")+"--->"+request.getParameter("age"));
//request.getRequestDispatcher("index.jsp").forward(request, response);
} }

(2)MainActivity.java

 package com.http2;

 import java.util.ArrayList;
import java.util.List; import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText; public class MainActivity extends Activity { //private Button getBtn,postBtn = null;
private EditText nameView,ageView = null;
private String baseUrl = "http://192.168.1.104:8080/AndroidServerTest/HandleRequest";
private String name,age = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); nameView = (EditText) findViewById(R.id.nameText);
ageView = (EditText) findViewById(R.id.ageText);
name = nameView.getText().toString();
age = ageView.getText().toString();
} public void getHttp(View view) {
String url = baseUrl + "?name=" + name + "&age=" + age;
HttpAsyncTask httpAsyncTask = new HttpAsyncTask(url, "get");
httpAsyncTask.execute("");
}
public void postHttp(View view) {
//post的参数会放在httpEntity里,所以不用拼url
List<String> parmas = new ArrayList<String>();
parmas.add(name);
parmas.add(age);
HttpAsyncTask httpAsyncTask = new HttpAsyncTask(baseUrl, "post", parmas);
httpAsyncTask.execute("");
} }

(3)HttpAsyncTask.java

 package com.http2;

 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair; import android.os.AsyncTask; public class HttpAsyncTask extends AsyncTask<String, Void, Void> { private String url;
private String method;
private List<String> params; public HttpAsyncTask(String url, String method) {
super();
this.url = url;
this.method = method;
}
public HttpAsyncTask(String url, String method, List<String> params) {
super();
this.url = url;
this.method = method;
this.params = params;
} @Override
protected Void doInBackground(String... params) {
if("get".equals(method))
sendGetHttpRequest(url);
else if("post".equals(method))
sendPostRequest(url, this.params);
return null;
} private void sendPostRequest(String url,List<String> params) {
System.out.println("sendPostRequest---->");
NameValuePair nameValuePair1 = new BasicNameValuePair("name", this.params.get(0));
NameValuePair nameValuePair2 = new BasicNameValuePair("age", this.params.get(1));
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(nameValuePair1);
nameValuePairs.add(nameValuePair2);
InputStream inputStream = null;
try {
//请求体
HttpEntity httpEntity = new UrlEncodedFormEntity(nameValuePairs);
//url不用带参数-->"?a=1&b=2"
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(httpEntity);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity respHttpEntity = httpResponse.getEntity();
inputStream = respHttpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
System.out.println(sb);
} catch (Exception e) {
e.printStackTrace();
}
} private void sendGetHttpRequest(String url) {
System.out.println("sendGetHttpRequest---->");
//生成一个请求对象
HttpGet httpGet = new HttpGet(url);
//生成一个Http客户端对象
HttpClient httpClient = new DefaultHttpClient();
InputStream inputStream = null;
//使用Http客户端发送请求对象
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
System.out.println(sb);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} }