gpt4 book ai didi

java - 如何从 Android 中返回 XML 或 JSON 的 url 获取数据

转载 作者:行者123 更新时间:2023-12-01 13:50:24 25 4
gpt4 key购买 nike

我是 Android 新手,但我在 Android 中使用 XML 解析器来解析我的应用程序中的 RSS。现在我想向我的服务器发送和接收新的应用程序数据。

我开发了 Web API 的服务器端,并对其进行了测试,到目前为止它正在运行。所以当我调用这样的网址时

http://URL/api/getQuery/value1/value2

我得到了这个 XML(以及需要的 JSON)。

<ArrayOfstring>
<string>4.5</string>
<string>Glu Mobile</string>
<string>4.2.0</string>
<string>1392/07/18</string>
<string>500</string>
<string>112MB</string>
<string>free</string>
<string>creator</string>
<string>describtion</string>
<string>similarapp</string>
</ArrayOfstring>

现在我想调用该 url 并接收 XML 或 JSON 字符串,然后将其解析为数组或列表。我怎样才能做到这一点?

最佳答案

使用volley库...这对你来说非常有用..这是给你的链接...下载并检查它,当你第一次做的时候要有耐心,之后会很容易...

https://github.com/ogrebgr/android_volley_examples

您可以使用Asynctask从服务器获取JSON数据。

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.System;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;

public class AsyncTaskActivity extends Activity implements OnClickListener {

Button btn;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
// because we implement OnClickListener we only have to pass "this"
// (much easier)
btn.setOnClickListener(this);
}

public void onClick(View view) {
// detect the view that was "clicked"
switch (view.getId()) {
case R.id.button1:
new LongOperation().execute("");
break;
}
}

private class LongOperation extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... params) {
String url = params[0];

HttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
request.setHeader("Content-Type", "text/xml");
HttpResponse response;
try {
response = httpClient.execute(request);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}

@Override
protected void onPostExecute(String result) {
// Result is in String Format
// you can use JSON api to convert into JSONObject

}

@Override
protected void onPreExecute() {}

@Override
protected void onProgressUpdate(Void... values) {}
}

}

关于java - 如何从 Android 中返回 XML 或 JSON 的 url 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20007209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com