休息 API Android 应用程序
Posted
技术标签:
【中文标题】休息 API Android 应用程序【英文标题】:Rest API Android Application 【发布时间】:2015-04-23 19:21:07 【问题描述】:我正在创建一个需要使用 HTTP 从 Web API 获取数据的 android 应用程序。它很可能是在我的应用程序中检索、处理然后更新 TextViews 的 JSON。我正在使用 SQL Server 数据库运行 MVC Web API 应用程序 (localhost)。我想在我的应用程序中检索数据并输出到 TextViews。我一直在关注本教程http://blog.strikeiron.com/bid/73189/Integrate-a-REST-API-into-Android-Application-in-less-than-15-minutes,因为我是 API 调用的新手,并且我不确定在您删除 API URL 后该怎么做。源码如下
fragment2_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:background="#D70B0D"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_
android:layout_
android:layout_gravity="center"
android:layout_marginTop="5dp"
android:text="@string/textView1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
<TextView
android:id="@+id/txtId"
android:layout_
android:layout_
android:text="@string/txtId"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:layout_margin="23dp"/>
<TextView
android:id="@+id/txtName"
android:layout_
android:layout_
android:text="@string/txtName"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:layout_margin="23dp"/>
<TextView
android:id="@+id/txtBirth"
android:layout_
android:layout_
android:text="@string/txtBirth"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:layout_margin="23dp"/>
<TextView
android:id="@+id/textView5"
android:layout_
android:layout_
android:layout_gravity="center"
android:layout_marginTop="5dp"
android:text="@string/textView5"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textStyle="bold" />
<TextView
android:id="@+id/txtMedHis"
android:layout_
android:layout_
android:text="@string/txtMedHis"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:layout_margin="23dp"/>
<TextView
android:id="@+id/txtMed"
android:layout_
android:layout_
android:text="@string/txtMed"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:layout_margin="23dp"/>
<TextView
android:id="@+id/txtAler"
android:layout_
android:layout_
android:text="@string/txtAler"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:layout_margin="23dp"/>
</LinearLayout>
Fragment2.java
package ie.itsligo.medication;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Fragment2 extends Fragment
public final static String apiURL = "http://localhost:63607/api/person/1";
TextView txtId;
TextView txtName;
TextView txtBirth;
TextView txtMedHis;
TextView txtMed;
TextView txtAler;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
View view = inflater.inflate(R.layout.fragment2_layout, container, false);
return view;
private class CallAPI extends AsyncTask<String, String, String>
@Override
protected String doInBackground(String... params)
String urlString=params[0]; // URL to call
String resultToDisplay = "";
InputStream in = null;
// HTTP Get
try
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
StringBuilder sb = new StringBuilder();
String line = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((line=reader.readLine())!=null)
sb.append(line);
reader.close();
String result = sb.toString();
Log.d("result", result);
JSONObject jsonResult = new JSONObject(result);
int id = jsonResult.getInt("ID");
String name = jsonResult.getString("FullName");
txtId = (TextView) getView().findViewById(R.id.txtId);
txtName = (TextView) getView().findViewById(R.id.txtName);
/*txtId.setText(ID);
txtName.setText(FullName);*/
catch (Exception e)
System.out.println(e.getMessage());
return e.getMessage();
return resultToDisplay;
protected void onPostExecute(String result)
// end CallAPI
LogCat
02-22 14:17:17.296: D/dalvikvm(19793): GC_CONCURRENT freed 159K, 13% free 10008K/11399K, paused 18ms+7ms, total 93ms
02-22 14:17:17.296: D/dalvikvm(19793): WAIT_FOR_CONCURRENT_GC blocked 17ms
02-22 14:17:17.466: I/Google Maps Android API(19793): Google Play services client version: 6587000
02-22 14:17:17.486: I/Google Maps Android API(19793): Google Play services package version: 6776034
02-22 14:17:17.606: D/dalvikvm(19793): GC_CONCURRENT freed 248K, 13% free 10298K/11783K, paused 13ms+7ms, total 76ms
02-22 14:17:17.606: D/dalvikvm(19793): WAIT_FOR_CONCURRENT_GC blocked 16ms
02-22 14:17:17.776: D/dalvikvm(19793): GC_CONCURRENT freed 163K, 12% free 10704K/12103K, paused 3ms+4ms, total 57ms
02-22 14:17:17.776: D/dalvikvm(19793): WAIT_FOR_CONCURRENT_GC blocked 10ms
02-22 14:17:17.986: D/dalvikvm(19793): GC_FOR_ALLOC freed 384K, 14% free 10988K/12679K, paused 80ms, total 80ms
02-22 14:17:18.127: D/dalvikvm(19793): GC_FOR_ALLOC freed 625K, 16% free 11321K/13447K, paused 75ms, total 76ms
02-22 14:17:18.717: D/dalvikvm(19793): GC_CONCURRENT freed 1004K, 16% free 12429K/14663K, paused 17ms+5ms, total 104ms
02-22 14:17:18.717: D/dalvikvm(19793): WAIT_FOR_CONCURRENT_GC blocked 46ms
02-22 14:17:19.137: D/dalvikvm(19793): GC_CONCURRENT freed 628K, 13% free 12860K/14727K, paused 19ms+6ms, total 111ms
02-22 14:17:19.137: D/dalvikvm(19793): WAIT_FOR_CONCURRENT_GC blocked 66ms
02-22 14:17:19.658: D/dalvikvm(19793): GC_CONCURRENT freed 272K, 10% free 13801K/15303K, paused 19ms+3ms, total 107ms
02-22 14:17:19.658: D/dalvikvm(19793): WAIT_FOR_CONCURRENT_GC blocked 39ms
02-22 14:17:19.798: I/dalvikvm(19793): Could not find method android.content.pm.PackageManager.getPackageInstaller, referenced from method com.google.android.gms.common.ew.c
02-22 14:17:19.798: W/dalvikvm(19793): VFY: unable to resolve virtual method 441: Landroid/content/pm/PackageManager;.getPackageInstaller ()Landroid/content/pm/PackageInstaller;
02-22 14:17:19.798: D/dalvikvm(19793): VFY: replacing opcode 0x6e at 0x000f
02-22 14:17:20.068: D/AbsListView(19793): Get MotionRecognitionManager
02-22 14:17:20.128: W/ActivityThread(19793): ClassLoader.loadClass: The class loader returned by Thread.getContextClassLoader() may fail for processes that host multiple applications. You should explicitly specify a context class loader. For example: Thread.setContextClassLoader(getClass().getClassLoader());
02-22 14:17:20.679: D/dalvikvm(19793): GC_CONCURRENT freed 1390K, 16% free 13958K/16583K, paused 13ms+4ms, total 189ms
02-22 14:17:20.679: D/dalvikvm(19793): WAIT_FOR_CONCURRENT_GC blocked 125ms
02-22 14:17:20.679: D/dalvikvm(19793): WAIT_FOR_CONCURRENT_GC blocked 79ms
02-22 14:17:20.679: D/dalvikvm(19793): WAIT_FOR_CONCURRENT_GC blocked 127ms
02-22 14:17:20.679: D/dalvikvm(19793): WAIT_FOR_CONCURRENT_GC blocked 130ms
02-22 14:17:20.869: D/AndroidRuntime(19793): Shutting down VM
02-22 14:17:20.869: W/dalvikvm(19793): threadid=1: thread exiting with uncaught exception (group=0x40e622a0)
02-22 14:17:20.899: E/AndroidRuntime(19793): FATAL EXCEPTION: main
02-22 14:17:20.899: E/AndroidRuntime(19793): java.lang.NullPointerException
02-22 14:17:20.899: E/AndroidRuntime(19793): at ie.itsligo.medication.Fragment2.onCreateView(Fragment2.java:39)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:486)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.view.View.measure(View.java:15288)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4876)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1396)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.view.View.measure(View.java:15288)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4876)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.view.View.measure(View.java:15288)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4876)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1396)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.view.View.measure(View.java:15288)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4876)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
02-22 14:17:20.899: E/AndroidRuntime(19793): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2397)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.view.View.measure(View.java:15288)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1974)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1217)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1390)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1113)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4481)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.view.Choreographer.doCallbacks(Choreographer.java:555)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.view.Choreographer.doFrame(Choreographer.java:525)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.os.Handler.handleCallback(Handler.java:615)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.os.Handler.dispatchMessage(Handler.java:92)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.os.Looper.loop(Looper.java:137)
02-22 14:17:20.899: E/AndroidRuntime(19793): at android.app.ActivityThread.main(ActivityThread.java:4867)
02-22 14:17:20.899: E/AndroidRuntime(19793): at java.lang.reflect.Method.invokeNative(Native Method)
02-22 14:17:20.899: E/AndroidRuntime(19793): at java.lang.reflect.Method.invoke(Method.java:511)
02-22 14:17:20.899: E/AndroidRuntime(19793): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
02-22 14:17:20.899: E/AndroidRuntime(19793): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
02-22 14:17:20.899: E/AndroidRuntime(19793): at dalvik.system.NativeStart.main(Native Method)
【问题讨论】:
【参考方案1】:假设你的服务器返回 json
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
所以你需要得到它。
StringBuilder sb = new StringBuilder(); // for final result
String line ="";
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); // read whatever is returned by server
while ((line=reader.readLine())!=null)
sb.append(line); // get response by line and append to StringBulder
reader.close();
String result = sb.toString(); //this is a response to parse.
Log.d("result", result); // check what is returned by server
解析来自服务器的响应。
JSONObject jsonResult = new JSONObject(result);// convert response to JSONObject
String main = jsonResult.getString("main"); // Smoke
int id = jsonResult.getInt("id") // 711 and so on.
将你的值输出到 TextView
textView.setText(main);
textView.setText(id);
【讨论】:
StringBuilder 中究竟存储了什么,我不确定其中的值是什么(“someKey”) StringBuilder - 存储 urlConnection 带给你的任何东西,在你的情况下它是 json。放 Log.d("结果", 结果);后字符串结果 = sb.toString(); 好的。我对此很陌生,所以我不确定输入什么值(“someKey”)以及如何将数据输出到我的应用程序中的 TextViews。 我更新了 Fragment2.java 我收到一个错误,我将值输出到 TextViews(括号内的值)并且我是否正确连接到 API 似乎有很多未使用代码。 Log.d("result", result);给我看看。它在您的控制台中打印什么【参考方案2】:为了更好的使用
RetroFit2.0
或者可以使用更多的托管(POST/GET)
RetroLet 1.5
//In your build.gradle
allprojects
repositories
...
maven url 'https://jitpack.io'
//In your application's build.gradle
dependencies
implementation 'com.github.Collabalist:RetroLet:1.5'
【讨论】:
以上是关于休息 API Android 应用程序的主要内容,如果未能解决你的问题,请参考以下文章
我需要构建一个休息客户端,以便在 Java 中以最佳性能进行 10k 次休息 api 调用/执行应用程序。任何有用的链接都会有所帮助