我是pretty新的Android和Java的世界,我想知道我是如何从Web API这里的 http://www.imdbapi.com/ 进入机器人。我应该使用JSON或XML?哪些步骤?首先,我想知道如何下载数据,然后如何将它解析为变量。任何样品code?
解决方案 的HttpClient HttpClient的=新DefaultHttpClient(); // prepare请求对象 HTTPGET HTTPGET =新HTTPGET(URL); //执行请求 HTT presponse响应; JSONArray ARR =新JSONArray(); 尝试{ 响应= httpclient.execute(HTTPGET); HttpEntity实体= response.getEntity(); 如果(实体= NULL&放大器;!&安培; response.getStatusLine()的getStatus code()== 200){ //一个简单的JSON响应读取 InputStream的河道= entity.getContent(); 字符串结果= convertStreamToString(插播广告); ARR =新JSONArray(结果); instream.close(); } }赶上(ClientProtocolException E){ // TODO自动生成catch块 Log.e(TAG,e.toString()); }赶上(IOException异常五){ // TODO自动生成catch块 Log.e(TAG,e.toString()); }赶上(JSONException E){ // TODO自动生成catch块 Log.e(TAG,e.toString()); } 返回ARR;公共静态字符串convertStreamToString(InputStream为){ 读者的BufferedReader =新的BufferedReader(新的InputStreamReader(是)); StringBuilder的SB =新的StringBuilder(); 串线= NULL; 尝试{ 而((行= reader.readLine())!= NULL){ sb.append(行+\\ n); } }赶上(IOException异常五){ Log.e(TAG +ERRORe.toString()); } {最后 尝试{ is.close(); }赶上(IOException异常五){ e.printStackTrace(); Log.e(TAG +ERRO,e.toString()); } } 返回sb.toString();}
至于解析,在这里你去:的http://开发商。 android.com/reference/org/json/package-summary.html
顺便说一句,这是很容易的所有谷歌上找到:)
I am pretty new to the world of Android and Java and I am wondering how I get data from the web api here http://www.imdbapi.com/ Into android. Should I use JSON or XML? What are the steps? Firstly I want to know how to download the data and then how to parse it to variables. Any sample code?
解决方案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();
}
As for parsing, here you go: http://developer.android.com/reference/org/json/package-summary.html
btw, this was all easily found on google : )