Android REST webservice 类
2024-08-25 22:12:55
App与后台交互,后台使用的是Jersey RESTful 服务。在APP端使用Android 内部集成的HttpClient接口,无需引入第三方jar包,
import org.apache.http.client.HttpClient;
在网上找到一个歪果人写Android端的REST类,网上文章引用挺多的。
Calling Web Services in Android using HttpClient
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; // 如何不是添加第一个key-value时
}
else
{
combinedParams += paramString; // 添加第一个key-value
}
}
} 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 stream will trigger connection release
instream.close();
} } catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
} private static String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder(); String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
调用实例:
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();
GET 方法没有问题,但是POST方法就需要考虑了,因为传递内容并不是只有
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); 比如自己的项目中使用的是:request.setEntity(new StringEntity(obj.toString(),HTTP.UTF_8)); 这里的 setEntity 内容是和setHeader 有关系的。 我的项目中应用的两种:postRequest.addHeader("Content-Type", "multipart/mixed"); post 图片的header
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploaded", bab);
postRequest.setEntity(reqEntity);
POST json 对象的:header 说明
rest.AddHeaders("Content-Type","application/json;charset=utf8");
Entity这样设置的:
request.setEntity(new StringEntity(obj.toString(),HTTP.UTF_8));
所以这个类写的通用型不行。
最新文章
- 解析 Json 相关
- Linux下Bash入门学习笔记
- JavaScript基础——使用数组
- 面向对象static静态的属性和方法的调用
- C#高级编程 反射 代码示例
- Flume数据传输事务分析[转]
- 指定URL,计算文件大小
- Hbase笔记——RowKey设计
- sql 语句左连接右连接小例子
- UVA 11389 The Bus Driver Problem
- JavaWeb学习笔记--跳转方法小结
- JavaScript函数学习要点总结(一)
- 使用 Visual Studio 对exe文件进行数字签名
- OCP-1Z0-051-题目解析-第13题
- java 协调同步的线程
- httpclient源码分析之MainClientExec
- 【STM32H7教程】第13章 STM32H7启动过程详解
- spring3:多数据源配置使用
- Hadoop问题:java.net.SocketException: Network is unreachable
- mongodb 怎样检测 安装成功 以及mongodb的一些增删改查命令