【移动应用开发技术】安卓接口请求实例_第1页
【移动应用开发技术】安卓接口请求实例_第2页
【移动应用开发技术】安卓接口请求实例_第3页
【移动应用开发技术】安卓接口请求实例_第4页
【移动应用开发技术】安卓接口请求实例_第5页
已阅读5页,还剩9页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

【移动应用开发技术】安卓接口请求实例

首先一个工具类package

com.luo.utils;

import

java.io.IOException;

import

java.io.InputStream;

import

java.io.UnsupportedEncodingException;

import

.URLDecoder;

import

java.util.Iterator;

import

java.util.List;

import

java.util.Map;

import

java.util.Set;

import

org.apache.http.HttpEntity;

import

org.apache.http.HttpResponse;

import

org.apache.http.HttpStatus;

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.params.HttpClientParams;

import

org.apache.http.impl.client.DefaultHttpClient;

import

org.apache.http.params.BasicHttpParams;

import

org.apache.http.params.HttpConnectionParams;

import

org.apache.http.params.HttpParams;

import

org.apache.http.params.HttpProtocolParams;

import

tocol.HTTP;

import

org.apache.http.util.EntityUtils;

import

android.content.Context;

import

android.graphics.Bitmap;

import

android.graphics.BitmapFactory;

import

.ConnectivityManager;

import

.http.AndroidHttpClient;

import

android.util.Log;

import

android.widget.Toast;

/**网络连接

*

@author

cnmobi-db

*

*/

public

class

MyConnect

{

private

static

HttpParams

httpParams;

private

static

HttpClient

httpClient;

/**get方式请求

*

@param

url

*

@param

params

*

@return

*/

public

static

String

doGet(String

url,

Map<String,

String>

params)

{

/*

建立HTTPGet对象

*/

String

paramStr

=

"";

Set<Map.Entry<String,

String>>

set

=

params.entrySet();

for

(Iterator<Map.Entry<String,

String>>

it

=

set.iterator();

it.hasNext();)

{

Map.Entry<String,

String>

entry

=

(Map.Entry<String,

String>)

it.next();

System.out.println(entry.getKey()

+

">"

+

entry.getValue());

paramStr

+=

paramStr

=

"&"

+

entry.getKey()

+

"="

+

entry.getValue();

}

if

(!paramStr.equals(""))

{

paramStr

=

paramStr.replaceFirst("&",

"?");

url

+=

paramStr;

}

Log.d("strResult",

url);

HttpGet

httpRequest

=

new

HttpGet(url);

String

strResult

=

"doGetError";

try

{

/*

发送请求并等待响应

*/

HttpResponse

httpResponse

=

httpClient.execute(httpRequest);

/*

若状态码为200

ok

*/

if

(httpResponse.getStatusLine().getStatusCode()

==

200)

{

/*

读返回数据

*/

strResult

=

EntityUtils.toString(httpResponse.getEntity());

}

else

{

// strResult

=

"Error

Response:

"

// +

httpResponse.getStatusLine().toString();

strResult

=

"404";

}

}

catch

(ClientProtocolException

e)

{

// strResult

=

e.getMessage().toString();

strResult

=

"404";

e.printStackTrace();

}

catch

(IOException

e)

{

// strResult

=

e.getMessage().toString();

strResult

=

"404";

e.printStackTrace();

}

catch

(Exception

e)

{

// strResult

=

e.getMessage().toString();

strResult

=

"404";

e.printStackTrace();

}

Log.d("strResult",

strResult);

return

strResult;

}

/**post方式请求

*

@param

session

*

@param

url

*

@param

params

*

@return

*/

public

static

String

doPost(String

session,String

url,

List<NameValuePair>

params)

{

String

www

=

url

+"?";

for(int

i

=0;

i<params.size();i++)

{

if(i

!=

params.size()-1)

www

=

www

+

params.get(i).toString()+"&";

else

www

=

www

+

params.get(i).toString();

}

Log.d("strResult","url>

"+www);

/*

建立HTTPPost对象

*/

HttpPost

httpRequest

=

new

HttpPost(url);

String

strResult

=

"doPostError";

try

{

/*

添加请求参数到请求对象

*/

httpRequest.setEntity(new

UrlEncodedFormEntity(params,

HTTP.UTF_8));

if(session

!=

null)

{

httpRequest.setHeader("Cookie",

session);

System.out.println(session);

}

/*

发送请求并等待响应

*/

HttpResponse

httpResponse

=

httpClient.execute(httpRequest);

/*

若状态码为200

ok

*/

if

(httpResponse.getStatusLine().getStatusCode()

==

200)

{

/*

读返回数据

*/

strResult

=

EntityUtils.toString(httpResponse.getEntity(),HTTP.UTF_8);

}

else

{

strResult

=

"404";//

"Error

Response:

"

+

//

httpResponse.getStatusLine().toString();

}

}

catch

(UnsupportedEncodingException

e)

{

strResult

=

"404";//

e.getMessage().toString();

e.printStackTrace();

}

catch

(ClientProtocolException

e)

{

strResult

=

"404";//

e.getMessage().toString();

e.printStackTrace();

}

catch

(IOException

e)

{

strResult

=

"404";//

e.getMessage().toString();

e.printStackTrace();

}

catch

(Exception

e)

{

strResult

=

"404";//

e.getMessage().toString();

e.printStackTrace();

}

Log.d("strResult",

strResult);

try

{

strResult

=

URLDecoder.decode(strResult,

HTTP.UTF_8);

}

catch

(UnsupportedEncodingException

e)

{

//

TODO

Auto-generated

catch

block

e.printStackTrace();

}

Log.d("strResult",

strResult);

return

strResult;

}

/**配置httpclient

*

@return

*/

public

static

HttpClient

getHttpClient()

{

//

创建

HttpParams

以用来设置

HTTP

参数(这一部分不是必需的)

httpParams

=

new

BasicHttpParams();

//

设置连接超时和

Socket

超时,以及

Socket

缓存大小

HttpConnectionParams.setConnectionTimeout(httpParams,

20

*

1000);

HttpConnectionParams.setSoTimeout(httpParams,

20

*

1000);

HttpConnectionParams.setSocketBufferSize(httpParams,

8192);

//

设置重定向,缺省为

true

HttpClientParams.setRedirecting(httpParams,

true);

//

设置

user

agent

String

userAgent

=

"Mozilla/5.0

(Windows;

U;

Windows

NT

5.1;

zh-CN;

rv:1.9.2)

Gecko/20100115

Firefox/3.6";

HttpProtocolParams.setUserAgent(httpParams,

userAgent);

//

创建一个

HttpClient

实例

httpClient

=

new

DefaultHttpClient(httpParams);

return

httpClient;

}

/**获取网络连通状态

*

@param

context

*

@return

*/

public

static

boolean

NetWorkStatus(Context

context)

{

boolean

netSataus

=

false;

ConnectivityManager

cwjManager

=

(ConnectivityManager)

context

.getSystemService(Context.CONNECTIVITY_SERVICE);

cwjManager.getActiveNetworkInfo();

if

(cwjManager.getActiveNetworkInfo()

!=

null)

{

netSataus

=

cwjManager.getActiveNetworkInfo().isAvailable();

}

if(!netSataus)

Toast.makeText(context,

"网络错误!",

Toast.LENGTH_SHORT).show();

return

netSataus;

}

/**获取网络图片

*

@param

url

*

@return

*/

public

static

Bitmap

loadImageFromInternet(String

url)

{

Bitmap

bitmap

=

null;

HttpClient

client

=

AndroidHttpClient.newInstance("Android");

HttpParams

params

=

client.getParams();

HttpConnectionParams.setConnectionTimeout(params,

3000);

HttpConnectionParams.setSocketBufferSize(params,

3000);

HttpResponse

response

=

null;

InputStream

inputStream

=

null;

HttpGet

httpGet

=

null;

try

{

httpGet

=

new

HttpGet(url);

response

=

client.execute(httpGet);

int

stateCode

=

response.getStatusLine().getStatusCode();

if

(stateCode

!=

HttpStatus.SC_OK)

{

return

bitmap;

}

HttpEntity

entity

=

response.getEntity();

if

(entity

!=

null)

{

try

{

inputStream

=

entity.getContent();

return

bitmap

=

BitmapFactory.decodeStream(inputStream);

}

finally

{

if

(inputStream

!=

null)

{

inputStream.close();

}

entity.consumeContent();

}

}

}

catch

(ClientProtocolException

e)

{

httpGet.abort();

e.printStackTrace();

}

catch

(IOException

e)

{

httpGet.abort();

e.printStackTrace();

}

finally

{

((AndroidHttpClient)

client).close();

}

return

bitmap;

}

}然后创建一个异步任务内部类class

GethispetsAsyncTask

extends

AsyncTask<Object,

Object,

Object>

{

ProgressDialog

dialog

=

ProgressDialog.show(HeActivity.this,

null,

"正在查询宠物信息,请稍后");

private

String

url;

private

String

token;

private

String

uid;

public

GethispetsAsyncTask(String

url,

String

token,

String

uid)

{

this.url

=

url;

this.token

=

token;

this.uid

=

uid;

}

@Override

protected

Object

doInBackground(Object...

params)

{

String

code

=

"1";

MyConnect.getHttpClient();

Map<String,

String>

parms

=

new

LinkedHashMap<String,

String>();

parms.put("token",

token);

parms.put("uid",

uid);

String

jsonContent

=

MyConnect.doGet(url,

parms);

try

{

JSONObject

jsonObject

=

new

JSONObject(jsonContent);

if

(jsonObject

!=

null)

{

code

=

jsonObject.getString("code");

if

(jsonObject.has("petArray"))

{

String

j1

=

jsonObject.getString("petArray");

JSONArray

j2

=

new

JSONArray(j1);

for

(int

i

=

0;

i

<

j2.length();

i++)

{

JSONObject

jsonObject2

=

j2.getJSONObject(i);

String

j3

=

jsonObject2.getInt("weight")

+

"

KG";

String

j4

=

jsonObject2.getString("nickname");

String

j5

=

jsonObject2.getString("birthday");

String

j6

=

jsonObject2.getString("breed");

HashMap<String,

String>

map

=

new

HashMap<String,

String>();

map.put("weight",

j3);

map.put("name",

j4);

map.put("bir",

j5);

map.put("kind",

j6);

hispetList.add(map);

}

}

if

(jsonObject.has("terminalArray"))

{

String

ter

=

jsonObject.getString("terminalArray");

JSONArray

termes

=

new

JSONArray(ter);

for

(int

i

=

0;

i

<

termes.length();

i++)

{

JSONObject

jsonObject3

=

termes.getJSONObject(i);

String

terid

=

jsonObject3.getString("terminalId");

String

dist

=

jsonObject3.getString("dist");

HashMap<String,

String>

map1

=

new

HashMap<String,

String>();

map1.put("terminalId",

terid);

map1.put("dist",

dist);

histerList.add(map1);

}

}

}

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论