在企业应用中,手机与企业数据的交互必不可少,在这里我们通过实例来描述android怎样调用.net webservice
第一步:vs2008建webservice ,贴出代码:
clsoptuser.cs
publicclass clsoptuser
{
{
//验证方法
publicbool Validate(string u, string p)
{
bool k =false;
SqlConnection userConn =new SqlConnection("连接字符");
userConn.Open();
SqlCommand userComm =new SqlCommand("select *from user", userConn);
SqlDataReader userDr = userComm.ExecuteReader();
string tmpuser, tmppass;
while (userDr.Read())
{
int userindex = userDr.GetOrdinal("user");
int passindex = userDr.GetOrdinal("password");
tmpuser = userDr.GetString(userindex);
tmppass = userDr.GetString(passindex);
publicbool Validate(string u, string p)
{
bool k =false;
SqlConnection userConn =new SqlConnection("连接字符");
userConn.Open();
SqlCommand userComm =new SqlCommand("select *from user", userConn);
SqlDataReader userDr = userComm.ExecuteReader();
string tmpuser, tmppass;
while (userDr.Read())
{
int userindex = userDr.GetOrdinal("user");
int passindex = userDr.GetOrdinal("password");
tmpuser = userDr.GetString(userindex);
tmppass = userDr.GetString(passindex);
//用户名和口令正确返回true
if ((tmpuser == u) && (tmppass == p))
{
k =true;
break;
}
}
return k;
}
}
if ((tmpuser == u) && (tmppass == p))
{
k =true;
break;
}
}
return k;
}
}
Service.cs
[WebMethod]
publicbool ValidateUsername(string username, string pass, string validate)
{
if (validate =="webservice验证码")
{
clsoptuser objoptuser =new clsoptuser();
return objoptuser.Validate(username, pass);
}
else
{
returnfalse;
}
}
publicbool ValidateUsername(string username, string pass, string validate)
{
if (validate =="webservice验证码")
{
clsoptuser objoptuser =new clsoptuser();
return objoptuser.Validate(username, pass);
}
else
{
returnfalse;
}
}
以上是服务器端的代码,把上面程序布署到IIS,布署以后可以用IE测试,具体布署我就不说了,网上到处有!
第二步:android客户端
android调用webservice 要用到ksoap2-android-assembly-2.4-jar-with-dependencies.jar一个包,到网上可下载,然后在Eclipce项目中添加处部jar
1、布局文件
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/login2"
android:gravity="bottom">
<LinearLayout android:id="@+id/LinearLayout02"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/labeluser"
android:text="@string/labelname"
android:textStyle="bold"
android:textSize="20sp">
</TextView>
<EditText android:layout_height="wrap_content"
android:id="@+id/EditTextUser"
android:width="150px"
android:layout_width="fill_parent">
</EditText>
</LinearLayout>
<LinearLayout android:id="@+id/LinearLayout03"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/labelpass"
android:text="登录密码:"
android:textStyle="bold"
android:textSize="20sp">
</TextView>
<EditText android:layout_height="wrap_content"
android:id="@+id/EditTextPassWord"
android:password="true"
android:layout_width="fill_parent">
</EditText>
</LinearLayout>
<LinearLayout android:id="@+id/LinearLayout04"
<LinearLayout android:id="@+id/LinearLayout02"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/labeluser"
android:text="@string/labelname"
android:textStyle="bold"
android:textSize="20sp">
</TextView>
<EditText android:layout_height="wrap_content"
android:id="@+id/EditTextUser"
android:width="150px"
android:layout_width="fill_parent">
</EditText>
</LinearLayout>
<LinearLayout android:id="@+id/LinearLayout03"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/labelpass"
android:text="登录密码:"
android:textStyle="bold"
android:textSize="20sp">
</TextView>
<EditText android:layout_height="wrap_content"
android:id="@+id/EditTextPassWord"
android:password="true"
android:layout_width="fill_parent">
</EditText>
</LinearLayout>
<LinearLayout android:id="@+id/LinearLayout04"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:gravity="center">
<CheckBox android:id="@+id/CheckBox01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="记住用户名和密码"
android:checked="true">
</CheckBox>
</LinearLayout>
<LinearLayout android:id="@+id/LinearLayout01"
</LinearLayout>
<LinearLayout android:id="@+id/LinearLayout01"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_gravity="bottom"
android:gravity="center">
<Button android:id="@+id/BtnLogin"
android:text="登 录"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1">
</Button>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/BtnExit"
android:text="退 出"
android:layout_weight="1">
</Button>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
想到每次进系统都要输入用户名和密码都恐怖(android的虚拟键盘确实不怎的),所以上面加了个"记住用户名和密码",方便下次不用输用户名和密码.
2、login.java
login.java
publicvoid ResponseOnClickLogin(String username,String password){
thread=new HttpThread(handlerwdy); //建立线程实例
HashMap <String ,Object> params=new HashMap<String ,Object>();
try{
package com.liwei.login;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import com.liwei.prohotel.clswdy.HttpThread;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
publicclass login extends Activity {
Button btnlogin,btnexit; //登录和退出按钮对像
EditText edituser,editpass; //用户名和密码输入框对象
boolean data=false; //调用webservice 近回的数据,验证成功true,失败false
HttpThread thread=null; //线程对像
String name=""; //用户名
String pass=""; //口令
/** Called when the activity is first created. */
@Override
publicvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnlogin=(Button)findViewById(R.id.BtnLogin); //获得用户名和密码按钮实例
btnexit=(Button)findViewById(R.id.BtnExit);
edituser=(EditText)findViewById(R.id.EditTextUser); //获得用户名和密码Edittext
editpass=(EditText)findViewById(R.id.EditTextPassWord);
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import com.liwei.prohotel.clswdy.HttpThread;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
publicclass login extends Activity {
Button btnlogin,btnexit; //登录和退出按钮对像
EditText edituser,editpass; //用户名和密码输入框对象
boolean data=false; //调用webservice 近回的数据,验证成功true,失败false
HttpThread thread=null; //线程对像
String name=""; //用户名
String pass=""; //口令
/** Called when the activity is first created. */
@Override
publicvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnlogin=(Button)findViewById(R.id.BtnLogin); //获得用户名和密码按钮实例
btnexit=(Button)findViewById(R.id.BtnExit);
edituser=(EditText)findViewById(R.id.EditTextUser); //获得用户名和密码Edittext
editpass=(EditText)findViewById(R.id.EditTextPassWord);
//获取上次保存的用户名和密码
SharedPreferences sp=getSharedPreferences("login",Context.MODE_PRIVATE);
String tempstr=sp.getString("username", "");
edituser.setText(tempstr);
editpass.setText(sp.getString("pass", ""));
SharedPreferences sp=getSharedPreferences("login",Context.MODE_PRIVATE);
String tempstr=sp.getString("username", "");
edituser.setText(tempstr);
editpass.setText(sp.getString("pass", ""));
//退出按钮点击事件
btnexit.setOnClickListener(new View.OnClickListener() {
publicvoid onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
//登录按钮点击事件
btnlogin.setOnClickListener(new View.OnClickListener() {
publicvoid onClick(View arg0) {
// TODO Auto-generated method stub
name=edituser.getText().toString();
pass=editpass.getText().toString();
ResponseOnClickLogin(name, pass);
}
});
}
btnexit.setOnClickListener(new View.OnClickListener() {
publicvoid onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
});
//登录按钮点击事件
btnlogin.setOnClickListener(new View.OnClickListener() {
publicvoid onClick(View arg0) {
// TODO Auto-generated method stub
name=edituser.getText().toString();
pass=editpass.getText().toString();
ResponseOnClickLogin(name, pass);
}
});
}
publicvoid ResponseOnClickLogin(String username,String password){
thread=new HttpThread(handlerwdy); //建立线程实例
HashMap <String ,Object> params=new HashMap<String ,Object>();
try{
String strvalidate="galyglxxxt";
strvalidate=new String(strvalidate.toString().getBytes(),"UTF-8");
params.put("username", username);//加入参数
params.put("pass", password);
params.put("validate", strvalidate);
}catch(Exception ex){
ex.printStackTrace();
}
String url="192.168.3.2:8080/loginweb/service.asmx";//webserivce地址
String nameSpace ="http://tempuri.org/"; //空间名,可修改
String methodName ="ValidateUsername"; //需调用webservice名称
thread.doStart(url, nameSpace, methodName, params); //启动线程
}
strvalidate=new String(strvalidate.toString().getBytes(),"UTF-8");
params.put("username", username);//加入参数
params.put("pass", password);
params.put("validate", strvalidate);
}catch(Exception ex){
ex.printStackTrace();
}
String url="192.168.3.2:8080/loginweb/service.asmx";//webserivce地址
String nameSpace ="http://tempuri.org/"; //空间名,可修改
String methodName ="ValidateUsername"; //需调用webservice名称
thread.doStart(url, nameSpace, methodName, params); //启动线程
}
//生成消息对象
Handler handlerwdy=new Handler(){
publicvoid handleMessage(Message m){
switch(m.what){
case1:
data=m.getData().getBoolean("data"); //从消息在拿出数据
if(data){
CheckBox cb=(CheckBox)findViewById(R.id.CheckBox01); //如果要保存用户名和密码
if(cb.isChecked())
{
SharedPreferences sp=getSharedPreferences("login",Context.MODE_PRIVATE);
Editor editor=sp.edit();
String tempname=name;
editor.putString("username", name);
editor.putString("pass", pass);
editor.commit();
}
else
{
SharedPreferences sp=getSharedPreferences("login",Context.MODE_PRIVATE);
Editor editor=sp.edit();
editor.putString("username", "");
editor.putString("pass", "");
editor.commit();
}
Handler handlerwdy=new Handler(){
publicvoid handleMessage(Message m){
switch(m.what){
case1:
data=m.getData().getBoolean("data"); //从消息在拿出数据
if(data){
CheckBox cb=(CheckBox)findViewById(R.id.CheckBox01); //如果要保存用户名和密码
if(cb.isChecked())
{
SharedPreferences sp=getSharedPreferences("login",Context.MODE_PRIVATE);
Editor editor=sp.edit();
String tempname=name;
editor.putString("username", name);
editor.putString("pass", pass);
editor.commit();
}
else
{
SharedPreferences sp=getSharedPreferences("login",Context.MODE_PRIVATE);
Editor editor=sp.edit();
editor.putString("username", "");
editor.putString("pass", "");
editor.commit();
}
//登录成功后的提示
Toast.makeText(prohotel.this, getString(R.string.login_message), Toast.LENGTH_SHORT)
.show();
Toast.makeText(prohotel.this, getString(R.string.login_message), Toast.LENGTH_SHORT)
.show();
//成功后界面要交给项目的主界面了
Intent in=new Intent(prohotel.this,promain.class);
//把用户名传给下一个activity
Bundle bundle =new Bundle();
bundle.putString("KEY_USERNAME",name);
in.putExtras(bundle);
login.this.startActivity(in);
}
else
{
Intent in=new Intent(prohotel.this,promain.class);
//把用户名传给下一个activity
Bundle bundle =new Bundle();
bundle.putString("KEY_USERNAME",name);
in.putExtras(bundle);
login.this.startActivity(in);
}
else
{
//验证不通过,给出个提示
SharedPreferences sp=getSharedPreferences("login",Context.MODE_PRIVATE);
Editor editor=sp.edit();
editor.putString("username", "");
editor.putString("pass", "");
editor.commit();
new AlertDialog.Builder(prohotel.this)
.setTitle(getString(R.string.login_message_title))
.setMessage(getString(R.string.login_message_title))
.setIcon(R.drawable.cancel)
.setNeutralButton(getString(R.string.login_button_text), new DialogInterface.OnClickListener() {
publicvoid onClick(DialogInterface dlg, int sumthin) {
// do nothing ?C it will close on its own
}
})
.show();
}
break;
case2:
SharedPreferences sp=getSharedPreferences("login",Context.MODE_PRIVATE);
Editor editor=sp.edit();
editor.putString("username", "");
editor.putString("pass", "");
editor.commit();
new AlertDialog.Builder(prohotel.this)
.setTitle(getString(R.string.login_message_title))
.setMessage(getString(R.string.login_message_title))
.setIcon(R.drawable.cancel)
.setNeutralButton(getString(R.string.login_button_text), new DialogInterface.OnClickListener() {
publicvoid onClick(DialogInterface dlg, int sumthin) {
// do nothing ?C it will close on its own
}
})
.show();
}
break;
case2:
//收到了调用出错的消息
new AlertDialog.Builder(prohotel.this)
.setTitle("出错:")
.setMessage(m.getData().getString("error"))
.setNeutralButton("Close", new DialogInterface.OnClickListener() {
publicvoid onClick(DialogInterface dlg, int sumthin) {
// do nothing ?C it will close on its own
}
})
.show();
break;
}
}
};
new AlertDialog.Builder(prohotel.this)
.setTitle("出错:")
.setMessage(m.getData().getString("error"))
.setNeutralButton("Close", new DialogInterface.OnClickListener() {
publicvoid onClick(DialogInterface dlg, int sumthin) {
// do nothing ?C it will close on its own
}
})
.show();
break;
}
}
};
//线程类
publicclass HttpThread extends Thread{
private Handler handle=null;
String url=null;
String nameSpace=null;
String methodName=null;
HashMap <String ,Object> params=null;
ProgressDialog progressDialog=null;
public HttpThread(Handler hander){
handle=hander;
}
//线程开始
publicvoid doStart(String url, String nameSpace, String methodName,
HashMap<String, Object> params) {
// 把参数传进来
this.url=url;
this.nameSpace=nameSpace;
this.methodName=methodName;
this.params=params;
//告诉使用者,请求开始了
progressDialog=new ProgressDialog(prohotel.this);
progressDialog.setTitle("网络连接");
progressDialog.setMessage("正在请求,请稍等......");
progressDialog.setIndeterminate(true);
//progressDialog=ProgressDialog.show(clswdy.this, "网络连接","正在验证,请稍等......",true,true);
progressDialog.setButton("取消", new DialogInterface.OnClickListener() {
publicvoid onClick(DialogInterface dialog, int i) {
progressDialog.cancel();
}
});
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
publicvoid onCancel(DialogInterface dialog) {
}
});
progressDialog.show();
this.start(); //线程开始了
}
/**
*/
@Override
publicvoid run() {
// TODO Auto-generated method stub
super.run();
try{
//web service请求,result为返回结果
boolean result= CallWebService();
if(result){
//取消进度对话框
progressDialog.dismiss();
//clswdy.this.setProgressBarIndeterminateVisibility(false);
//构造消息,验证通过了
Message message=handle.obtainMessage();
Bundle b=new Bundle();
message.what=1; //这里是消息的类型
b.putBoolean("data", true); //这里是消息传送的数据
message.setData(b);
handle.sendMessage(message);
}
else
{
progressDialog.dismiss();
Message message=handle.obtainMessage();
Bundle b=new Bundle();
message.what=1;
b.putBoolean("data", false);
message.setData(b);
handle.sendMessage(message);
}
}catch(Exception ex){
progressDialog.dismiss();
// 构造消息,程序出错了
Message message=handle.obtainMessage();
Bundle b=new Bundle();
message.what=2;
b.putString("error", ex.getMessage());
message.setData(b);
handle.sendMessage(message);
}finally{
}
}
/**
*
*/
protectedboolean CallWebService() throws Exception{
String SOAP_ACTION = nameSpace + methodName;
boolean response=false;
SoapObject request=new SoapObject(nameSpace,methodName);
// boolean request=false;
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true; //.net 支持
// 参数
if(params !=null&&!params.isEmpty() ){
for(Iterator it=params.entrySet().iterator();it.hasNext();){
Map.Entry e=(Entry) it.next();
request.addProperty(e.getKey().toString(),e.getValue());
}
}
envelope.bodyOut=request;
//
AndroidHttpTransport androidHttpTrandsport=new AndroidHttpTransport(url);
//HttpTransportSE androidHttpTransport = new HttpTransportSE(url);
SoapObject result=null;
try{
//web service请求
androidHttpTrandsport.call(SOAP_ACTION, envelope);
//得到返回结果
Object temp=envelope.getResult();
response=Boolean.parseBoolean(temp.toString());
}catch(Exception ex){
throw ex;
}
return response;
}
}
}
publicclass HttpThread extends Thread{
private Handler handle=null;
String url=null;
String nameSpace=null;
String methodName=null;
HashMap <String ,Object> params=null;
ProgressDialog progressDialog=null;
public HttpThread(Handler hander){
handle=hander;
}
//线程开始
publicvoid doStart(String url, String nameSpace, String methodName,
HashMap<String, Object> params) {
// 把参数传进来
this.url=url;
this.nameSpace=nameSpace;
this.methodName=methodName;
this.params=params;
//告诉使用者,请求开始了
progressDialog=new ProgressDialog(prohotel.this);
progressDialog.setTitle("网络连接");
progressDialog.setMessage("正在请求,请稍等......");
progressDialog.setIndeterminate(true);
//progressDialog=ProgressDialog.show(clswdy.this, "网络连接","正在验证,请稍等......",true,true);
progressDialog.setButton("取消", new DialogInterface.OnClickListener() {
publicvoid onClick(DialogInterface dialog, int i) {
progressDialog.cancel();
}
});
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
publicvoid onCancel(DialogInterface dialog) {
}
});
progressDialog.show();
this.start(); //线程开始了
}
/**
*/
@Override
publicvoid run() {
// TODO Auto-generated method stub
super.run();
try{
//web service请求,result为返回结果
boolean result= CallWebService();
if(result){
//取消进度对话框
progressDialog.dismiss();
//clswdy.this.setProgressBarIndeterminateVisibility(false);
//构造消息,验证通过了
Message message=handle.obtainMessage();
Bundle b=new Bundle();
message.what=1; //这里是消息的类型
b.putBoolean("data", true); //这里是消息传送的数据
message.setData(b);
handle.sendMessage(message);
}
else
{
progressDialog.dismiss();
Message message=handle.obtainMessage();
Bundle b=new Bundle();
message.what=1;
b.putBoolean("data", false);
message.setData(b);
handle.sendMessage(message);
}
}catch(Exception ex){
progressDialog.dismiss();
// 构造消息,程序出错了
Message message=handle.obtainMessage();
Bundle b=new Bundle();
message.what=2;
b.putString("error", ex.getMessage());
message.setData(b);
handle.sendMessage(message);
}finally{
}
}
/**
*
*/
protectedboolean CallWebService() throws Exception{
String SOAP_ACTION = nameSpace + methodName;
boolean response=false;
SoapObject request=new SoapObject(nameSpace,methodName);
// boolean request=false;
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true; //.net 支持
// 参数
if(params !=null&&!params.isEmpty() ){
for(Iterator it=params.entrySet().iterator();it.hasNext();){
Map.Entry e=(Entry) it.next();
request.addProperty(e.getKey().toString(),e.getValue());
}
}
envelope.bodyOut=request;
//
AndroidHttpTransport androidHttpTrandsport=new AndroidHttpTransport(url);
//HttpTransportSE androidHttpTransport = new HttpTransportSE(url);
SoapObject result=null;
try{
//web service请求
androidHttpTrandsport.call(SOAP_ACTION, envelope);
//得到返回结果
Object temp=envelope.getResult();
response=Boolean.parseBoolean(temp.toString());
}catch(Exception ex){
throw ex;
}
return response;
}
}
}
以上验证程序需要访问网络,别忘了在AndroidManifest.xml加入 <uses-permission android:name="android.permission.INTERNET" />
1
0
(请您对文章做出评价)
posted on 2012-02-01 10:50 freeliver54 阅读(1617) 评论(1) 编辑 收藏
评论
#1楼[楼主]
Calling Web Services in Android using HttpClient
http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/
Now I am pretty new to Android and Java in general but I feel I’ve come up with a nice simple way to make requests to web services and APIs (and plain html pages if you want). The class uses the org.apache.http library which is included in Android.
This is the code for the class.
public class RestClient {
private ArrayList <NameValuePair> params;
private ArrayList <NameValuePair> headers;
private String url;
private int responseCode;
private String message;
private String response;
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
public RestClient(String url)
{
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void AddParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}
public void AddHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}
public void Execute(RequestMethod method) throws Exception
{
switch(method) {
case GET:
{
//add parameters
String combinedParams = "";
if(!params.isEmpty()){
combinedParams += "?";
for(NameValuePair p : params)
{
String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),”UTF-8″);
if(combinedParams.length() > 1)
{
combinedParams += "&" + paramString;
}
else
{
combinedParams += paramString;
}
}
}
HttpGet request = new HttpGet(url + combinedParams);
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
executeRequest(request, url);
break;
}
case POST:
{
HttpPost request = new HttpPost(url);
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
if(!params.isEmpty()){
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(request, url);
break;
}
}
}
private void executeRequest(HttpUriRequest request, String url)
{
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input strea will trigger connection release
instream.close();
}
utdown();
ce();
{
ace();
amToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilde StringBuilder()
Strin
Here is an example of how I use the class to call the Google Analytics API. I use the AddParam methods to add query string / post values and the AddHeader method to add headers to the request. RequestMethod is a simple enum with GET and POST values.
view sourceprint?
RestClient client = new RestClient(LOGIN_URL);
client.AddParam("accountType", "GOOGLE");
client.AddParam("source", "tboda-widgalytics-0.1");
client.AddParam("Email", _username);
client.AddParam("Passwd", _password);
client.AddParam("service", "analytics");
client.AddHeader("GData-Version", "2");
try {
client.Execute(RequestMethod.POST);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
The class also exposes the Http response code and message which are important when using some Restful APIs. I know could definitely improve/extend on this code and would love to hear from those more experienced in Java and Android than myself.
http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/
Now I am pretty new to Android and Java in general but I feel I’ve come up with a nice simple way to make requests to web services and APIs (and plain html pages if you want). The class uses the org.apache.http library which is included in Android.
This is the code for the class.
public class RestClient {
private ArrayList <NameValuePair> params;
private ArrayList <NameValuePair> headers;
private String url;
private int responseCode;
private String message;
private String response;
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
public RestClient(String url)
{
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void AddParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}
public void AddHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}
public void Execute(RequestMethod method) throws Exception
{
switch(method) {
case GET:
{
//add parameters
String combinedParams = "";
if(!params.isEmpty()){
combinedParams += "?";
for(NameValuePair p : params)
{
String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),”UTF-8″);
if(combinedParams.length() > 1)
{
combinedParams += "&" + paramString;
}
else
{
combinedParams += paramString;
}
}
}
HttpGet request = new HttpGet(url + combinedParams);
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
executeRequest(request, url);
break;
}
case POST:
{
HttpPost request = new HttpPost(url);
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
if(!params.isEmpty()){
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(request, url);
break;
}
}
}
private void executeRequest(HttpUriRequest request, String url)
{
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input strea will trigger connection release
instream.close();
}
utdown();
ce();
{
ace();
amToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilde StringBuilder()
Strin
Here is an example of how I use the class to call the Google Analytics API. I use the AddParam methods to add query string / post values and the AddHeader method to add headers to the request. RequestMethod is a simple enum with GET and POST values.
view sourceprint?
RestClient client = new RestClient(LOGIN_URL);
client.AddParam("accountType", "GOOGLE");
client.AddParam("source", "tboda-widgalytics-0.1");
client.AddParam("Email", _username);
client.AddParam("Passwd", _password);
client.AddParam("service", "analytics");
client.AddHeader("GData-Version", "2");
try {
client.Execute(RequestMethod.POST);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
The class also exposes the Http response code and message which are important when using some Restful APIs. I know could definitely improve/extend on this code and would love to hear from those more experienced in Java and Android than myself.