0
我对Android和Java的世界相当陌生,我想知道如何从这里的web api获取数据http://www.imdbapi.com/进入android。 我应该使用JSON还是XML? 步骤是什么?首先,我想知道如何下载数据,然后如何解析变量。 任何示例代码?JSON,XML连接到Android的web api?
我对Android和Java的世界相当陌生,我想知道如何从这里的web api获取数据http://www.imdbapi.com/进入android。 我应该使用JSON还是XML? 步骤是什么?首先,我想知道如何下载数据,然后如何解析变量。 任何示例代码?JSON,XML连接到Android的web api?
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
JSONArray arr = new JSONArray();
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null && response.getStatusLine().getStatusCode() == 200) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
arr=new JSONArray(result);
instream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Log.e(TAG,e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG,e.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e(TAG,e.toString());
}
return arr;
public static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
Log.e(TAG + "ERROR",e.toString());
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG + "ERRO",e.toString());
}
}
return sb.toString();
}
至于用于解析,在这里你去:http://developer.android.com/reference/org/json/package-summary.html
顺便说一句,这是所有容易在谷歌发现:)
不知道它是那么容易在Java解析JSON:o –
此运行在14 sdk版本?如果要在2.3.3上运行,我该怎么办?而不是JSON获得这些参数的替代方法? –
这段代码在android studio的TAG中抛出错误。 ''TAG'在'android.support.v4.app.Fragment'中有专用权限'' – Shivam