很久没有码字了,今天跟大家分享一个模拟get和post方法的工具类,在安卓应用中很多都需要跟服务器进行数据交互,这需要两方面的配合,首先服务器端会给应用提供一些数据交互的接口,可是怎样在应用中去调用呢?这就需要用到get和post方法了,下面是自己总结并且一直在用的两个工具类,请看代码:

用来模拟get方法:

package com.standopen.exceptionsdk;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.os.Handler;
import android.os.Message; public class doGet { private Context ctx;
private String url;
private thread_callback callback; public doGet(Context ctx, String url, thread_callback back) {
this.ctx = ctx;
this.url = url;
this.callback = back;
post_thread th = new post_thread(ctx, url);
th.start(); } public class post_thread extends Thread {
private String url;
private Context ctx; public post_thread(Context ctx, String url) {
this.url = url;
this.ctx = ctx;
} Handler handler = new Handler() { @Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
// int type = Integer.parseInt(msg.obj.toString());
String back = msg.obj.toString();
callback.callback(back);
}
}; @Override
public void run() {
// TODO Auto-generated method stub
super.run();
String str = null;
try {
str = post(url);
Message msg1 = handler.obtainMessage();
msg1.obj = str;
handler.sendMessage(msg1); } catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } @Override
public synchronized void start() {
// TODO Auto-generated method stub
super.start();
} public String post(String url) throws ClientProtocolException,
IOException { String str = "";
HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream is = response.getEntity().getContent();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
if ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
byte[] b = baos.toByteArray();
is.close();
baos.close();
str = new String(b, "utf-8"); }
return str;
} }
}

用来模拟post方法:

package com.standopen.exceptionsdk;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.os.Handler;
import android.os.Message; public class doPost { private Context ctx;
private String url;
private thread_callback callback;
private ArrayList<NameValuePair> data = null; public doPost(Context ctx, String url, ArrayList<NameValuePair> data,
thread_callback back) {
this.ctx = ctx;
this.url = url;
this.callback = back;
this.data = data;
post_thread th = new post_thread(ctx, url, data);
th.start(); } public class post_thread extends Thread {
private String url;
private Context ctx; private ArrayList<NameValuePair> data; public post_thread(Context ctx, String url,
ArrayList<NameValuePair> data) {
this.url = url;
this.ctx = ctx;
this.data = data;
} Handler handler = new Handler() { @Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
// int type = Integer.parseInt(msg.obj.toString());
String back = msg.obj.toString();
callback.callback(back);
}
}; @Override
public void run() {
// TODO Auto-generated method stub
super.run();
String str = null;
try {
str = post(url);
Message msg1 = handler.obtainMessage();
msg1.obj = str;
handler.sendMessage(msg1); } catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } @Override
public synchronized void start() {
// TODO Auto-generated method stub
super.start();
} public String post(String url) throws ClientProtocolException,
IOException { String str = "";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(data, "utf-8"));
HttpResponse response = client.execute(post);
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream is = response.getEntity().getContent();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
if ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
byte[] b = baos.toByteArray();
is.close();
baos.close();
str = new String(b); }
return str;
} }
}

 用来数据回调的接口:

package com.standopen.exceptionsdk;

public interface thread_callback {
public void callback(String back);
}

  从数据库中获取到数据后,就要对数据进行解析,提取到需要的数据进行使用,这些也非常简单,下次再分享。

分享两个模拟get和post方法的工具类,让应用能够与服务器进行数据交互的更多相关文章

  1. Go/Python/Erlang编程语言对比分析及示例 基于RabbitMQ.Client组件实现RabbitMQ可复用的 ConnectionPool(连接池) 封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!

    Go/Python/Erlang编程语言对比分析及示例   本文主要是介绍Go,从语言对比分析的角度切入.之所以选择与Python.Erlang对比,是因为做为高级语言,它们语言特性上有较大的相似性, ...

  2. 调用jdbc已经写成的方法----jdbc工具类抽取方式三

    package jdbc_demo3; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.R ...

  3. 调用jdbc已经写成的方法----jdbc工具类抽取方式二

    先创建db.properties driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/web08?useUnicode=true& ...

  4. 调用jdbc已经写成的方法----jdbc工具类抽取方式一

    package web09; /*获取连接和释放资源的方法 */ import java.sql.Connection; import java.sql.DriverManager; import j ...

  5. Java模拟http请求调用远程接口工具类

    package ln; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamRea ...

  6. Java模拟http请求远程调用接口工具类

    package ln; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamRea ...

  7. 一个对称加密、解密的方法C#工具类

    封装了一个对称加解密的类,用私钥和密钥加解密 using System; using System.Collections.Generic; using System.Text; using Syst ...

  8. 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!

    using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; usi ...

  9. java读取配置文件方法以及工具类

    第一种方式 : java工具类读取配置文件工具类 只是案例代码  抓取异常以后的代码自己处理 import java.io.FileNotFoundException; import java.io. ...

随机推荐

  1. 使用C#选择文件夹、打开文件夹、选择文件

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  2. uva 1421

    稍微有点新意的二分 #include<cstdio> #include<cstring> #include<algorithm> #include<cmath ...

  3. [BEC][hujiang] Lesson03 Unit1:Working life ---Grammar & Listening & Vocabulary

    3 Working life p8 Grammar Gerund and infinitive(动名词和不定式) 一般而言:        1 动词后面接动名词还是不定式没有特定规则,主要取决于语言习 ...

  4. 2013流行Python项目汇总

    2013流行Python项目汇总 转自:http://www.kankanews.com/ICkengine/archives/102963.shtml Python作为程序员的宠儿,越来越得到人们的 ...

  5. PowerDesigner15(16)在生成SQL时报错Generation aborted due to errors detected during the verification of the mod

    1.用PowerDesigner15建模,在Database—>Generate Database (或者用Ctrl+G快捷键)来生产sql语句,却提示“Generation aborted d ...

  6. Spring MVC 与 web开发

    转载:http://coderbee.net/index.php/java/20140719/959 项目组用了 Spring MVC 进行开发,觉得对里面的使用方式不是很满意,就想,如果是我来搭建开 ...

  7. Qt之界面数据存储与获取(使用setUserData()和userData())

    在GUI开发中,往往需要在界面中存储一些有用的数据,这些数据可以来配置文件.注册表.数据库.或者是server. 无论来自哪里,这些数据对于用户来说都是至关重要的,它们在交互过程中大部分都会被用到,例 ...

  8. WPF之小动画二

    上一篇文章简单介绍了动画的定义方法和一些控制动画的方法,并没有涉及复杂属性的动画处理方式,本文将继续动画的其它方面的使用. 写在前面(对于一些动画操作时候的建议): 1.如果希望某个元素从显示到消失, ...

  9. android系统平台显示驱动开发简要:LCD常用接口篇『二』

    平台信息:内核:linux3.4.39系统:android4.4 平台:S5P4418(cortex a9) 作者:瘋耔(欢迎转载,请注明作者) 欢迎指正错误,共同学习.共同进步!! 关注博主新浪博客 ...

  10. Python爬虫和情感分析简介

    摘要 这篇短文的目的是分享我这几天里从头开始学习Python爬虫技术的经验,并展示对爬取的文本进行情感分析(文本分类)的一些挖掘结果. 不同于其他专注爬虫技术的介绍,这里首先阐述爬取网络数据动机,接着 ...