一、代码

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请求的更多相关文章

  1. ANDROID_MARS学习笔记_S04_003_用HttpClent发http请求

    一.代码 1.xml(1)activity_main.xml <TextView android:layout_width="wrap_content" android:la ...

  2. Tornado学习笔记(一) helloword/多进程/启动参数

    前言 当你觉得你过得很舒服的时候,你肯定没有在进步.所以我想学习新的东西,然后选择了Tornado.因为我觉得Tornado更匹配目前的我的综合素质. Tornado学习笔记系列主要参考<int ...

  3. 学习笔记之Struts2—浅析接收参数

    最近自己通过视频与相关书籍的学习,对action里面接收参数做一些总结与自己的理解. 0.0.接收参数的(主要)方法   使用Action的属性接收参数 使用DomainModel接收参数 使用Mod ...

  4. Python学习笔记(四)Python函数的参数

    Python的函数除了正常使用的必选参数外,还可以使用默认参数.可变参数和关键字参数. 默认参数 基本使用 默认参数就是可以给特定的参数设置一个默认值,调用函数时,有默认值得参数可以不进行赋值,如: ...

  5. Java学习笔记7---父类构造方法有无参数对子类的影响

    子类不继承父类的构造方法,但父类的构造方法对子类构造方法的创建有影响.具体来说就是: ①.当父类没有无参构造方法时,子类也不能有无参构造方法:且必须在子类构造方法中显式以super(参数)的形式调用父 ...

  6. 【Java学习笔记】函数的可变参数

    package p2; public class ParamterDemo { public static void main(String[] args) { int sum1 = add(4,5) ...

  7. ANDROID_MARS学习笔记_S02_001_Spinner

    1.strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> < ...

  8. ANDROID_MARS学习笔记_S02_006_APPWIDGET3_AppWidget发送广播及更新AppWidget

    一.简介 二.代码1.xml(1)example_appwidget.xml <?xml version="1.0" encoding="utf-8"?& ...

  9. ANDROID_MARS学习笔记_S02_006_APPWIDGET2_PendingIntent及RemoteViews实现widget绑定点击事件

    一.代码流程 1.ExampleAppWidgetProvider的onUpdate(Context context, AppWidgetManager appWidgetManager, int[] ...

随机推荐

  1. .net+easyui系列--按钮

    easyui提供了各种按钮样式,包括搜索.新增.保存.删除等 <a id="btn" href="#" class="easyui-linkbu ...

  2. web开发学习之旅---html第二天

    一.转义符 一些字符在html中拥有特殊的含义,比如小于号(<)用于定义 HTML 标签的开始.如果我们希望浏览器正确地显示这些字符,我们必须在 HTML 源码中插入转义符. 分类 二.html ...

  3. ACM——进制转换

    http://acm.njupt.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=1012 进制转换 时间限制(普通/Jav ...

  4. DLL中导出STL模板类的问题

    接上一篇. 上一篇的dll在编译过程中一直有一个警告warning C4251: ‘CLASS_TEST::m_structs’ : class ‘std::vector<_Ty>’ ne ...

  5. HTML解析引擎:Jumony

    Jumony Core首先提供了一个近乎完美的HTML解析引擎,其解析结果无限逼近浏览器的解析结果.不论是无结束标签的元素,可选结束标签的元素,或是标记属性,或是CSS选择器和样式,一切合法的,不合法 ...

  6. 我的微软.net演进路线图

    原文地址:我的微软.net演进路线图 我的微软.net演进路线图 我的这几年,编程方面主要是跟在微软旗下奔跑的,主要语言是C# 集成开发环境(IDE) .NET Framework版本 介入年份 Vi ...

  7. C# 多线程(二) 线程同步基础

    本系列的第一篇简单介绍了线程的概念以及对线程的一些简单的操作,从这一篇开始讲解线程同步,线程同步是多线程技术的难点.线程同步基础由以下几个部分内容组成 1.同步要领(Synchronization E ...

  8. IDE开发<LER-Studio>(1)::UI设计

    LER-Studio主要使用Microsoft Ribbon界面(fluentUI),大致为Office 2007 black. 首先创建MFC程序,基于多文档视图,Ribbon界面,基类选择CVie ...

  9. leetcode344——Reverse String(C++)

    Write a function that takes a string as input and returns the string reversed. Example:Given s = &qu ...

  10. SETLOCAL

    Quote from: http://ss64.com/nt/setlocal.html SETLOCAL Set options to control the visibility of envir ...