码迷,mamicode.com
首页 > 移动开发 > 详细

Android -- 获取接口数据的三个方法

时间:2017-01-04 09:34:41      阅读:321      评论:0      收藏:0      [点我收藏+]

标签:long   ems   响应   同步   tput   oca   cancel   nis   class   

1.   compile ‘com.loopj.android:android-async-http:1.4.9‘:

  AsyncHttpClient client = new AsyncHttpClient();
   RequestParams params = new RequestParams();
 params.addHeader(HTTP.CONTENT_TYPE,
               "application/x-www-form-urlencoded;charset=UTF-8");
        params.put("loginer_id", "4363");
        params.put("tzcodelist", "0047,0046,0043");
        params.put("downlimit", "1");
        params.put("uplimit", "100");


        client.post(url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, String response) {
                super.onSuccess(statusCode, headers, response);
                Toast.makeText(getApplication(),"同步数据完成",Toast.LENGTH_SHORT).show();
                Toast.makeText(getApplication(), response, Toast.LENGTH_LONG).show();

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //在主线程中执行
                        Toast.makeText(getApplication(),"同步数据完成",Toast.LENGTH_SHORT).show();
                    }
                }, 500);

            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                Toast.makeText(getApplication(), "同步数据失败", Toast.LENGTH_LONG).show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //在主线程中执行
                        Toast.makeText(getApplication(), "同步数据失败", Toast.LENGTH_LONG).show();
                    }
                }, 50);

            }



        });

2.   compile ‘org.xutils:xutils:3.2.2‘:

 String url = "http://222.169.11.226:7000/WebServiceAndroidcm.asmx/GetCminfoByTzcodeList";
       // String url = "http://123.232.120.76:6011/api/UserInfo?xq_id=1";
        RequestParams params = new RequestParams(url);
        params.addHeader(HTTP.CONTENT_TYPE,
               "application/x-www-form-urlencoded;charset=UTF-8");
        params.addBodyParameter("loginer_id", "4363");
        params.addBodyParameter("tzcodelist", "0047,0046,0043");
        params.addBodyParameter("downlimit", "1");
        params.addBodyParameter("uplimit", "100");

        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onCancelled(Callback.CancelledException arg0) {

                Toast.makeText(getApplication(), "cancle", Toast.LENGTH_SHORT).show();
            }

            // 注意:如果是自己onSuccess回调方法里写了一些导致程序崩溃的代码,也会回调道该方法,因此可以用以下方法区分是网络错误还是其他错误
            // 还有一点,网络超时也会也报成其他错误,还需具体打印出错误内容比较容易跟踪查看
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

                Toast.makeText(x.app(), "fuk", Toast.LENGTH_SHORT).show();
                if (ex instanceof HttpException) { // 网络错误
                    HttpException httpEx = (HttpException) ex;
                    int responseCode = httpEx.getCode();
                    String responseMsg = httpEx.getMessage();
                    String errorResult = httpEx.getResult();
                    Toast.makeText(getApplication(), errorResult, Toast.LENGTH_SHORT).show();
                    // ...
                } else { // 其他错误
                    // ...
                    Toast.makeText(x.app(), "funck you", Toast.LENGTH_SHORT).show();
                }

            }

            // 不管成功或者失败最后都会回调该接口
            @Override
            public void onFinished() {
             //   Toast.makeText(getApplication(), "llafda", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(String arg0) {
                Toast.makeText(getApplication(), "chegngonng le ", Toast.LENGTH_SHORT).show();
            }



        });

 

3. 自带的http:

   运用原生Java Api发送简单的Get请求、Post请求步骤

  1. 通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection)
  2. 设置请求的参数
  3. 发送请求
  4. 以输入流的形式获取返回内容
  5. 关闭输入流
package me.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;

public class HttpRequestor {
    
    private String charset = "utf-8";
    private Integer connectTimeout = null;
    private Integer socketTimeout = null;
    private String proxyHost = null;
    private Integer proxyPort = null;
    
    /**
     * Do GET request
     * @param url
     * @return
     * @throws Exception
     * @throws IOException
     */
    public String doGet(String url) throws Exception {
        
        URL localURL = new URL(url);
        
        URLConnection connection = this.openConnection(localURL);
        HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
        
        httpURLConnection.setRequestProperty("Accept-Charset", charset);
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;
        //响应失败
        if (httpURLConnection.getResponseCode() >= 300) {
            throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
        }
        
        try {
            inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);
            
            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }
            
        } finally {
            
            if (reader != null) {
                reader.close();
            }
            
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            
            if (inputStream != null) {
                inputStream.close();
            }
            
        }

        return resultBuffer.toString();
    }
    
    /**
     * Do POST request
     * @param url
     * @param parameterMap
     * @return
     * @throws Exception 
     */
    public String doPost(String url, Map parameterMap) throws Exception {
        
        /* Translate parameter map to parameter date string */
        StringBuffer parameterBuffer = new StringBuffer();
        if (parameterMap != null) {
            Iterator iterator = parameterMap.keySet().iterator();
            String key = null;
            String value = null;
            while (iterator.hasNext()) {
                key = (String)iterator.next();
                if (parameterMap.get(key) != null) {
                    value = (String)parameterMap.get(key);
                } else {
                    value = "";
                }
                
                parameterBuffer.append(key).append("=").append(value);
                if (iterator.hasNext()) {
                    parameterBuffer.append("&");
                }
            }
        }
        
        System.out.println("POST parameter : " + parameterBuffer.toString());
        
        URL localURL = new URL(url);
        
        URLConnection connection = this.openConnection(localURL);
        HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
        
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Accept-Charset", charset);
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length()));
        
        OutputStream outputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;
        
        try {
            outputStream = httpURLConnection.getOutputStream();
            outputStreamWriter = new OutputStreamWriter(outputStream);
            
            outputStreamWriter.write(parameterBuffer.toString());
            outputStreamWriter.flush();
            //响应失败
            if (httpURLConnection.getResponseCode() >= 300) {
                throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
            }
            //接收响应流
         inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);
            
            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }
            
        } finally {
            
            if (outputStreamWriter != null) {
                outputStreamWriter.close();
            }
            
            if (outputStream != null) {
                outputStream.close();
            }
            
            if (reader != null) {
                reader.close();
            }
            
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            
            if (inputStream != null) {
                inputStream.close();
            }
            
        }

        return resultBuffer.toString();
    }

    private URLConnection openConnection(URL localURL) throws IOException {
        URLConnection connection;
        if (proxyHost != null && proxyPort != null) {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
            connection = localURL.openConnection(proxy);
        } else {
            connection = localURL.openConnection();
        }
        return connection;
    }
    
    /**
     * Render request according setting
     * @param request
     */
    private void renderRequest(URLConnection connection) {
        
        if (connectTimeout != null) {
            connection.setConnectTimeout(connectTimeout);
        }
        
        if (socketTimeout != null) {
            connection.setReadTimeout(socketTimeout);
        }
        
    }

    /*
     * Getter & Setter
     */
    public Integer getConnectTimeout() {
        return connectTimeout;
    }

    public void setConnectTimeout(Integer connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public Integer getSocketTimeout() {
        return socketTimeout;
    }

    public void setSocketTimeout(Integer socketTimeout) {
        this.socketTimeout = socketTimeout;
    }

    public String getProxyHost() {
        return proxyHost;
    }

    public void setProxyHost(String proxyHost) {
        this.proxyHost = proxyHost;
    }

    public Integer getProxyPort() {
        return proxyPort;
    }

    public void setProxyPort(Integer proxyPort) {
        this.proxyPort = proxyPort;
    }

    public String getCharset() {
        return charset;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }
    
}

 

Android -- 获取接口数据的三个方法

标签:long   ems   响应   同步   tput   oca   cancel   nis   class   

原文地址:http://www.cnblogs.com/mafeng/p/6247309.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!