首页 > 代码库 > Android -- 获取接口数据的三个方法
Android -- 获取接口数据的三个方法
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 one rror(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请求步骤
- 通过统一资源定位器(java.net.URL)获取连接器(java.net.URLConnection)
- 设置请求的参数
- 发送请求
- 以输入流的形式获取返回内容
- 关闭输入流
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 -- 获取接口数据的三个方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。