Android入门:用HttpClient模拟HTTP的GET和POST请求
一、HttpClient介绍
二、服务器端代码
- 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"/>
- 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() {
- @Override
- public 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");
- }
- }
Android入门:用HttpClient模拟HTTP的GET和POST请求的更多相关文章
- 用HttpClient模拟HTTP的GET和POST请求(转)
本文转自:http://blog.csdn.net/xiazdong/article/details/7724349 一.HttpClient介绍 HttpClient是用来模拟HTTP请求的,其 ...
- 一步步教你为网站开发Android客户端---HttpWatch抓包,HttpClient模拟POST请求,Jsoup解析HTML代码,动态更新ListView
本文面向Android初级开发者,有一定的Java和Android知识即可. 文章覆盖知识点:HttpWatch抓包,HttpClient模拟POST请求,Jsoup解析HTML代码,动态更新List ...
- Android入门(十二)SQLite事务、升级数据库
原文链接:http://www.orlion.ga/610/ 一.事务 SQLite支持事务,看一下Android如何使用事务:比如 Book表中的数据都已经很老了,现在准备全部废弃掉替换成新数据,可 ...
- HttpClient模拟http请求
Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且 ...
- 【转】Xamarin.Android 入门之:Xamarin+vs2015 环境搭建
Xamarin.Android 入门之:Xamarin+vs2015 环境搭建 一.前言 此篇博客主要写了如何使用搭建xamarin开发的环境,防止我自己万一哪天电脑重装系统了,可以直接看这篇博客 ...
- android 入门 006(sqlite增删改查)
android 入门 006(sqlite增删改查) package cn.rfvip.feb_14_2_sqlite; import android.content.Context; import ...
- android 入门 005(登录记住)
android 入门 005(登录记住) <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android ...
- Android入门:绑定本地服务
一.绑定服务介绍 前面文章中讲过一般的通过startService开启的服务,当访问者关闭时,服务仍然存在: 但是如果存在这样一种情况:访问者需要与服务进行通信,则我们需要将访问者与服务进行绑定: ...
- Android入门视频推荐
marschen老师的Android入门视频推荐网址: 1.Android应用程序开发视频教程(重制版)第一季 2.Android应用开发视频教程(重制版)第二季 2.marschen老师的个人微 ...
随机推荐
- hdu1162Eddy's picture
http://acm.hdu.edu.cn/showproblem.php?pid=1162 最小生成树 #include<iostream> #include<stdio.h> ...
- P1024 外星人的密码数字
P1024 外星人的密码数字 时间: 1000ms / 空间: 131072KiB / Java类名: Main 描述 XXXX年突然有外星人造访,但大家语言不通,不过科学家们经过研究发现外星 ...
- 【mysql的编程专题】触发器
类似tp里面的数据模型回调接口,在数据表增删改的前或后触发执行其他的预订的sql; 一个触发器要具备4要素: 1.监视地点 -- 要执行触发器的表 2.监视事件 -- 由什么DML事件来牵引 3.触发 ...
- LR_问题_无法使用LR的Controller,提示缺少license
问题描述 无法使用LR的Controller,提示缺少license 问题解决 使用开始->所有程序->HP LoadRunner->loadrunner,在打开界面的左上角选择co ...
- The Introduction of Java Memory Leaks
One of the most significant advantages of Java is its memory management. You simply create objects a ...
- WPF中Timer与DispatcherTimer类的区别
前几天在WPF中写了一个轨迹回放的功能,我想稍微做过类似项目的,都晓得采用一个时间控件或者时间对象作为调度器,我在这么做的时候,出现了问题,于是将程序中的Timer换成了DispatchTimer,然 ...
- java教材
教材blog !!http://www.w3cschool.cc/java/java-tutorial.html ok http://www.douban.com/group/topic/ ...
- jboolean
bool为C中变量类型,jboolean 为JNI中变量类型,boolean为Java中变量类型:jboolean在C语言的定义为:typedef unsigned char jboolean;uns ...
- Xcode学习
http://www.cnblogs.com/ygm900/p/3488881.html
- 宏HASH_GET_NEXT
/*******************************************************************//** Gets the next struct in a h ...