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();
}
}
} }
ANDROID_MARS学习笔记_S04_004_用HTTPCLENT发带参数的get和post请求的更多相关文章
- ANDROID_MARS学习笔记_S04_003_用HttpClent发http请求
一.代码 1.xml(1)activity_main.xml <TextView android:layout_width="wrap_content" android:la ...
- Tornado学习笔记(一) helloword/多进程/启动参数
前言 当你觉得你过得很舒服的时候,你肯定没有在进步.所以我想学习新的东西,然后选择了Tornado.因为我觉得Tornado更匹配目前的我的综合素质. Tornado学习笔记系列主要参考<int ...
- 学习笔记之Struts2—浅析接收参数
最近自己通过视频与相关书籍的学习,对action里面接收参数做一些总结与自己的理解. 0.0.接收参数的(主要)方法 使用Action的属性接收参数 使用DomainModel接收参数 使用Mod ...
- Python学习笔记(四)Python函数的参数
Python的函数除了正常使用的必选参数外,还可以使用默认参数.可变参数和关键字参数. 默认参数 基本使用 默认参数就是可以给特定的参数设置一个默认值,调用函数时,有默认值得参数可以不进行赋值,如: ...
- Java学习笔记7---父类构造方法有无参数对子类的影响
子类不继承父类的构造方法,但父类的构造方法对子类构造方法的创建有影响.具体来说就是: ①.当父类没有无参构造方法时,子类也不能有无参构造方法:且必须在子类构造方法中显式以super(参数)的形式调用父 ...
- 【Java学习笔记】函数的可变参数
package p2; public class ParamterDemo { public static void main(String[] args) { int sum1 = add(4,5) ...
- ANDROID_MARS学习笔记_S02_001_Spinner
1.strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> < ...
- ANDROID_MARS学习笔记_S02_006_APPWIDGET3_AppWidget发送广播及更新AppWidget
一.简介 二.代码1.xml(1)example_appwidget.xml <?xml version="1.0" encoding="utf-8"?& ...
- ANDROID_MARS学习笔记_S02_006_APPWIDGET2_PendingIntent及RemoteViews实现widget绑定点击事件
一.代码流程 1.ExampleAppWidgetProvider的onUpdate(Context context, AppWidgetManager appWidgetManager, int[] ...
随机推荐
- FPGA异步时钟设计中的同步策略
1 引言 基于FPGA的数字系统设计中大都推荐采用同步时序的设计,也就是单时钟系统.但是实际的工程中,纯粹单时钟系统设计的情况很少,特别是设计模块与外围芯片的通信中,跨时钟域的情况经常不可避免. ...
- 3s自动跳转到登陆界面
cdn资源 Bootstrap是Twitter推出的一个用于前端开发的开源工具包.它由Twitter的设计师Mark Otto和Jacob Thornton合作开发,是一个CSS/HTML框架.Boo ...
- eclipse 手动安装皮肤
关于自动使用eclipse 主题不成功的给出现在手动的安装方法和jar包 http://pan.baidu.com/s/1kVNEiYr http://pan.baidu.com/s/1cyTZrS ...
- .NET笔记系列:LAMBDA表达式常用写法
这里主要是将数据库中的常用操作用LAMBDA表达式重新表示了下,用法不多,但相对较常用,等有时间了还会扩展,并将查询语句及LINQ到时也一并重新整理下: 1.select语句:books.Select ...
- SQL 编译与重编译
编译的含义 当SQLSERVER收到任何一个指令,包括查询(query).批处理(batch).存储过程.触发器(trigger) .预编译指令(prepared statement)和动态SQL语句 ...
- 0基础学习ios开发笔记第二天
C语言的基本结构 c语言的入口函数是main函数. main函数的返回值行业标准是int return 数字:返回值 每条语句最后以分号结尾 注释:行注释.块注释 int main(void) { / ...
- IDC机房动力环境设备维护
高低压配电 空调 ...
- 'DEVENV' is not recognized as an internal or external command,
使用命令行 DEVENV 编译c# 工程, C:\MyProject>DEVENV "MyProject.sln" /build Release /useenv'DEVENV ...
- greenlet代码解读
协程 上次已经讲解了协程的的实现方法,和我对协程的一些理解.这里指我就先以代码说明协程的运行.def test1(): print 12 (2) gr2.switch() ...
- mysql主从之主键冲突
收到短信报警,两台数据库都报slave同步失败了,先说明一下环境,架构:lvs+keepalived+amoeba+mysql,主主复制,单台写入, 主1:192.168.0.223(写) 主2:19 ...