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));

所以这个类写的通用型不行。

最新文章

  1. 解析 Json 相关
  2. Linux下Bash入门学习笔记
  3. JavaScript基础——使用数组
  4. 面向对象static静态的属性和方法的调用
  5. C#高级编程 反射 代码示例
  6. Flume数据传输事务分析[转]
  7. 指定URL,计算文件大小
  8. Hbase笔记——RowKey设计
  9. sql 语句左连接右连接小例子
  10. UVA 11389 The Bus Driver Problem
  11. JavaWeb学习笔记--跳转方法小结
  12. JavaScript函数学习要点总结(一)
  13. 使用 Visual Studio 对exe文件进行数字签名
  14. OCP-1Z0-051-题目解析-第13题
  15. java 协调同步的线程
  16. httpclient源码分析之MainClientExec
  17. 【STM32H7教程】第13章 STM32H7启动过程详解
  18. spring3:多数据源配置使用
  19. Hadoop问题:java.net.SocketException: Network is unreachable
  20. mongodb 怎样检测 安装成功 以及mongodb的一些增删改查命令

热门文章

  1. unity, read text file
  2. unity, 不要试图用rigidbody.Sleep()停止rigidbody
  3. PHP的CURLOPT_POSTFIELDS参数使用数组和字符串的区别
  4. NGUI 取ScrollView中遮罩区域4个点
  5. JVM性能调优入门
  6. C++语言基础(20)-模板的非类型参数
  7. FileStream常用的属性和方法 (转)
  8. js 阻止事件冒泡 支持所有主流浏览器
  9. 凑成整数x----二进制枚举
  10. sublimtext3 自定义编译环境