我是android的新手.我实际上是一家创业公司的实习生,所以我要自己学习.我的团队负责人刚刚让我编写一个应用程序来从Android应用程序调用REST API.他让我从一个api响应中读取状态值,并在新活动中显示其值.我其实不知道我应该做什么.到目前为止,我只学过基本的东西,比如在活动之间传递价值.请给我一个很好的教程,或者给我一个想法.
Yog*_*dra 68
请使用android-async-http库.
以下链接逐步解释了所有内容.
http://loopj.com/android-async-http/
以下是示例应用:
创建一个类:
public class HttpUtils {
private static final String BASE_URL = "http://api.twitter.com/1/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(url, params, responseHandler);
}
public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(url, params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
Run Code Online (Sandbox Code Playgroud)
通话方式:
RequestParams rp = new RequestParams();
rp.add("username", "aaa"); rp.add("password", "aaa@123");
HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
Log.d("asd", "---------------- this is response : " + response);
try {
JSONObject serverResp = new JSONObject(response.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
}
});
Run Code Online (Sandbox Code Playgroud)
请在您的清单文件中授予Internet权限.
<uses-permission android:name="android.permission.INTERNET" />
Run Code Online (Sandbox Code Playgroud)
如果需要,您可以在build.gradle文件中添加compile 'com.loopj.android:android-async-http:1.4.9'for Header[]和compile 'org.json:json:20160212'for JSONObject.
| 归档时间: |
|
| 查看次数: |
134221 次 |
| 最近记录: |