分享两个模拟get和post方法的工具类,让应用能够与服务器进行数据交互
很久没有码字了,今天跟大家分享一个模拟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方法的工具类,让应用能够与服务器进行数据交互的更多相关文章
- Go/Python/Erlang编程语言对比分析及示例 基于RabbitMQ.Client组件实现RabbitMQ可复用的 ConnectionPool(连接池) 封装一个基于NLog+NLog.Mongo的日志记录工具类LogUtil 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!
Go/Python/Erlang编程语言对比分析及示例 本文主要是介绍Go,从语言对比分析的角度切入.之所以选择与Python.Erlang对比,是因为做为高级语言,它们语言特性上有较大的相似性, ...
- 调用jdbc已经写成的方法----jdbc工具类抽取方式三
package jdbc_demo3; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.R ...
- 调用jdbc已经写成的方法----jdbc工具类抽取方式二
先创建db.properties driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/web08?useUnicode=true& ...
- 调用jdbc已经写成的方法----jdbc工具类抽取方式一
package web09; /*获取连接和释放资源的方法 */ import java.sql.Connection; import java.sql.DriverManager; import j ...
- Java模拟http请求调用远程接口工具类
package ln; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamRea ...
- Java模拟http请求远程调用接口工具类
package ln; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamRea ...
- 一个对称加密、解密的方法C#工具类
封装了一个对称加解密的类,用私钥和密钥加解密 using System; using System.Collections.Generic; using System.Text; using Syst ...
- 分享基于MemoryCache(内存缓存)的缓存工具类,C# B/S 、C/S项目均可以使用!
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Caching; usi ...
- java读取配置文件方法以及工具类
第一种方式 : java工具类读取配置文件工具类 只是案例代码 抓取异常以后的代码自己处理 import java.io.FileNotFoundException; import java.io. ...
随机推荐
- 【数位DP】bzoj1026: [SCOI2009]windy数
1026: [SCOI2009]windy数 Time Limit: 1 Sec Memory Limit: 162 MBSubmit: 4163 Solved: 1864[Submit][Sta ...
- DataGridView 列自适应宽度 设置
代码: Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; 或者设置DataGridView的AutoSizeColu ...
- textarea中限制输入字符长度(实用版)
textarea称文本域,又称文本区,即有滚动条的多行文本输入控件,在网页的提交表单中经常用到.与单行文本框text控件不同,它不能通过maxlength属性来限制字数,为此必须寻求其他方法来加以限制 ...
- ADO.net--杂七杂八(一)
private void BtnConnectDataBase_Click(object sender, RoutedEventArgs e) { string connectionString = ...
- Python中pass语句的作用
http://mianshi.fenzhi.com/post/1529.html pass语句什么也不做,一般作为占位符或者创建占位程序,pass语句不会执行任何操作,比如:while False:p ...
- http://doc.okbase.net/congcong68/archive/112508.html
http://doc.okbase.net/congcong68/archive/112508.html
- tinyXml在linux下的使用
[下载] 一.下载 xml 软件包:tinyxml_2_6_2.zipTinyxml(轻量级 c++)下载地址:http://sourceforge.net/projects/tinyxml/?sou ...
- HDU1875——畅通工程再续(最小生成树:Kruskal算法)
畅通工程再续 Description相信大家都听说一个“百岛湖”的地方吧,百岛湖的居民生活在不同的小岛中,当他们想去其他的小岛时都要通过划小船来实现.现在政府决定大力发展百岛湖,发展首先要解决的问题当 ...
- node.js模块之fs文件系统
fs 模块是文件操作的封装,它提供了文件的读取.写入.更名.删除.遍历目录.链接等 POSIX 文件系统操作.与其他模块不同的是,fs 模块中所有的操作都提供了异步的和同步的两个版本, 例如读取文件内 ...
- Svn忽略配置
Debug bin obj *.user *.suo *.vspscc *.scc *.o *.lo *.la *.al .libs *.so *.so.[0-9]* *.a *.pyc *.pyo ...