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 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请求步骤
- 通过统一资源定位器(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;
} }
异步get(石秦):
new Thread(new Runnable() {
String url = "http://123.232.120.76:6011/api/Login?user_name=zll&pwd=1";
Message msg = new Message();
@Override
public void run() {
try {
URL urlString = new URL(url);
//打开url
HttpURLConnection connection = (HttpURLConnection)urlString.openConnection();
//请求超时
connection.setConnectTimeout(2000);
//读取超时
connection.setReadTimeout(2000); //获取请求成功响应码
if (connection.getResponseCode() == 200) { InputStream is = connection.getInputStream();
String json = StreamUtil.streamtoString(is);
// json.replace("[", "");
// json.replace("]", "");
Log.d("json", json);
System.out.print(json);
JSONObject jsonObject = new JSONObject(json); }
} catch (MalformedURLException e) {
e.printStackTrace();
msg.what = URLERROR;
Log.d("url", "aaaa");
} catch (IOException e) {
e.printStackTrace();
msg.what = IOERROR;
Log.d("io", "qqqqq");
} catch (JSONException e) {
e.printStackTrace();
msg.what = JSONERROR;
Log.d("jsonfailure", "qqqqq");
}
}
}).start();
Android -- 获取接口数据的三个方法的更多相关文章
- php获取POST数据的三种方法
方法一,$_POST $_POST或$_REQUEST存放的是PHP以key=>value的形式格式化以后的数据. $_POST方式是通过 HTTP POST 方法传递的变量组成的数组,是自动全 ...
- Java中获取键盘输入值的三种方法
Java中获取键盘输入值的三种方法 Java程序开发过程中,需要从键盘获取输入值是常有的事,但Java它偏偏就没有像c语言给我们提供的scanf(),C++给我们提供的cin()获取键盘输入值 ...
- Thinkphp3.2.3框架下封装公共的函数,例如封装CURL函数来获取接口数据
当我们需要在控制层调用相同的封装函数时,写多次相同的函数,显得代码十分的拉杂,不精简: TP框架有一个很好的机制,可以再Common定义一个function.php函数,当我们在控制层调用的时候直接调 ...
- PHP获取POST数据的几种方法汇总
一.PHP获取POST数据的几种方法 方法1.最常见的方法是:$_POST['fieldname']; 说明:只能接收Content-Type: application/x-www-form-urle ...
- php curl请求和获取接口数据
curl请求和获取接口数据 class ToolModel{ /** * [http 调用接口函数] * @Author GeorgeHao * @param string $url [接口地址] * ...
- js获取当前时间戳的三个方法
var time1 = Date.parse(new Date()); var time2 = new Date().valueOf(); var time3 = new Date().getTime ...
- 关于Hive创建分区目录且能查到数据的三种方法
关于Hive创建分区目录且能查到数据的三种方法 1. 使用dfs -mkdir 和 dfs -put 分别创建分区目录和上传数据,此时执行msck repair table 表名 命令就能查询到数据 ...
- PHP获取POST数据的三种方式
一.PHP获取POST数据的几种方法 方法1.最常见的方法是:$_POST['fieldname']; 说明:只能接收Content-Type: application/x-www-form-urle ...
- Ajax获取接口数据,url拼接参数跳转页面,js获取上一级页面参数给本页面
1.Ajax获取接口数据 function demo(){ //假设请求参数 var requestBody = [{ "name":"zhang", &quo ...
随机推荐
- Performance Monitor3:监控SQL Server的内存压力
SQL Server 使用的资源受到操作系统的调度,同时,SQL Server在内部实现了一套调度算法,用于管理从操作系统获取的资源,主要是对内存和CPU资源的调度.一个好的数据库系统,必定在内存中缓 ...
- 【转载】C#怎么判断字符是不是汉字
支持并尊重原创!原文地址:http://jingyan.baidu.com/article/2c8c281deb79ed0008252af1.html 判断一个字符是不是汉字通常有三种方法,第1种用 ...
- Debian8安装Vim8
1 安装vim需要的库 apt-get build-dep vim-gtk apt-get install libncurses5-dev mercurial 2 下载Vim8 apt-get i ...
- Interview website
https://www.interviewcake.com http://www.leetcode.com
- c3p0连接数据库的3种方式
c3p0连接数据库的3种方式,这里以mysql为例 1. 直接用set方法设置参数, 基本方法 ComboPooledDataSource dataSource = new ComboPooledDa ...
- python爬虫成长之路(一):抓取证券之星的股票数据
获取数据是数据分析中必不可少的一部分,而网络爬虫是是获取数据的一个重要渠道之一.鉴于此,我拾起了Python这把利器,开启了网络爬虫之路. 本篇使用的版本为python3.5,意在抓取证券之星上当天所 ...
- ssh改https为ssh
第一:设置Git的user name和email: 第二:然后生成key 这里会生成两个文件 id_rsa 和 id_rsa.pub 第三:登录你的GITHUB账号 看下图 第四:测试下是否成功 第五 ...
- Css3新特性应用之视觉效果
一.单侧阴影 box-shadow属性的应用,格式:h-shadow v-shadow blur spread color inset属性取值介绍 h-sahdow:水平阴影的位置,允许负值 v-sh ...
- iOS---关于UIWebView
1.加载的web界面可以自由收缩 webView.scalesPageToFit = YES;
- 网络安全——数据的加密与签名,RSA介绍
一. 密码概述 发送者对明文进行加密然后生成密文,接受者再对密文解密得到明文的过程. 现在使用的所有加密算法都是公开的!但是密钥肯定不是公开的. 1 散列(哈希)函数 通常有MD5.SHA1.SHA2 ...