简体   繁体   English

如何获得 XML 响应

[英]How to get XML response

How can I get XML response from website?如何从网站获取 XML 响应? Website is not mine, so I'm going to parse it.网站不是我的,所以我要解析它。 I'm using WebView and parse code by JSONP.我正在使用 WebView 并通过 JSONP 解析代码。 But there are some needful buttons, when I click them I get XML response.但是有一些必要的按钮,当我单击它们时,我会收到 XML 响应。 Please help me, I have no idea how to do it请帮帮我,我不知道该怎么做

To send a request from your java code use AsyncTask or Android-Async-Http , set the accept header as application/xml and pass it to your webview.要从您的 java 代码发送请求,请使用AsyncTaskAndroid-Async-Http ,将接受标头设置为 application/xml 并将其传递给您的 webview。

Here an example of a generic request using an Async Http Client :这是使用Async Http Client的通用请求的示例:

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;
    }

And here an example with AsyncTask :这里有一个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();
            } 
        }
    }
}

If instead you want to send a GET request using javascript within a webview you can use something like:相反,如果您想在 webview 中使用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);
}

or use jquery (or other frameworks like angularJS for more complex webviews).或使用 jquery(或其他框架,如 angularJS,用于更复杂的 web 视图)。 Example using jquery :使用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());
    }
});

Anyhow cross domain xml from javascript is a no-no unless you have control over the application that is spitting out the XML and can use a formatting trick to 'fool' the script into parsing it as JSON.无论如何,来自 javascript 的跨域 xml 是一个禁忌,除非您可以控制吐出 XML 的应用程序,并且可以使用格式化技巧来“愚弄”脚本将其解析为 JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM