zoukankan      html  css  js  c++  java
  • Android REST webservice 类

      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 + "
    ");
                }
            } 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));


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


  • 相关阅读:
    深度优先和广度优先
    水管工游戏(深度优先)
    炸弹人
    广度优先(迷宫找人)
    System.Data.Entity.Core.MetadataException: 无法加载指定的无数据资源
    Element Cascader 级联选择器 单选操作优化
    Windows服务 ProjectInstaller 获取 路径
    Quartz.NET ScheduledFireTimeUtc 当超过1分钟时出现的问题。
    记录:一个SQL SERVER奇怪的问题。
    log4.net 配置
  • 原文地址:https://www.cnblogs.com/igoogleyou/p/restandroid.html
Copyright © 2011-2022 走看看