如何从网站获取XML响应?网站不是我的,所以我要去解析它。我使用WebView并通过JSONP解析代码。但是有一些需要的按钮,当我点击它们时,我得到了XML响应。请帮帮我,我不知道怎么做
答案 0 :(得分:0)
要使用AsyncTask或Android-Async-Http从您的java代码发送请求,请将accept标头设置为application / xml并将其传递给您的网络视图。
以下是使用异步Http客户端的通用请求的示例:
import com.loopj.android.http.*;
import cz.msebera.android.httpclient.Header;
public class AppConnector {
private String url;
private void setUrl(String url){
this.url = url;
}
public ListenableFuture<String> getSomething(){
Log.d("App", "get something..");
return launchHttpCall();
}
public ListenableFuture<String> launchHttpCall(){
final SettableFuture<String> future = SettableFuture.create();
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
Log.d("App", "GET request towards: "+url);
asyncHttpClient
.get( url, new TextHttpResponseHandler()
{
@Override
public void onSuccess(int statusCode, Header[] headers, String responseBody)
{
Log.d("App", "HTTP CLIENT SUCCESS..");
future.set("Response Success. statusCode:"+statusCode+", Response body: "+responseBody);
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable error){
Log.d("MeeRBA", "HTTP CLIENT FAILURE.. ");
future.setException(error);
}
});
return future;
}
这是 AsyncTask :
的示例class WebAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return goGoConnect(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Log.d("App", "Post execute..");
// textView.setText(result);
// or callback
}
private String goGoConnect(String myurl) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved web page content.
int len = 5000;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(3000);
conn.setConnectTimeout(5000); // millis
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
conn.setRequestProperty("Content-Type", "application/xml");
// Starts the query
conn.connect();
int response = conn.getResponseCode();
is = conn.getInputStream();
// Convert the InputStream into a string
InputStreamReader reader = null;
reader = new InputStreamReader(is, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
String contentAsString = new String(buffer);
Log.d("App", "The response content is: "+contentAsString);
return contentAsString;
}catch(Exception e){
Log.d("App", "Exception:"+e);
return "Eception: >>"+e;
// Makes sure that the InputStream is closed after the app is finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
}
如果您想在网页浏览中使用 javascript 发送GET请求,则可以使用以下内容:
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
或使用jquery(或其他框架,如angularJS,用于更复杂的webview)。 使用 jquery :
的示例$.ajax({
type: "Get",
url: "http://domain.com/function?Data=1234567890",
xhrFields: {withCredentials: true},
dataType: "JSONP text xml",
contentType: "application/xml",
cache: false,
success: function(xml)
{
alert($(this).find('ResponseStatus').text());
}
});
无论如何,来自javascript的跨域xml是禁止的,除非您可以控制正在吐出XML的应用程序并且可以使用格式化技巧来“欺骗”脚本将其解析为JSON。