0
我無法從url解析xml,該擴展名不以.xml結尾。然而,使用下面的代碼我可以成功解析相同的XML保存到/ res /原始。無法解析xml,不擴展名爲.xml
或者當它使用.xml擴展名創建時,例如this或 「api.androidhive.info/pizza/?format=xml」。
同時加入/?format=xml
到url的末尾並不能解決問題。
我認爲這與獲取HttpResponse有關,但我無法用我當前的代碼解決問題。我需要能夠檢索xml並解析它,即使沒有.xml擴展名也是如此。
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
return doc;
}
這裏是我的logcat的結果:
07-25 17:54:39.090: I/INFO(29276): Content:{"Message":"An error has occurred.","ExceptionMessage":"Value cannot be null.\r\nParameter name: entity","ExceptionType":"System.ArgumentNullException","StackTrace":" at System.Data.Entity.ModelConfiguration.Utilities.RuntimeFailureMethods.Requires(Boolean condition, String userMessage, String conditionText)\r\n at System.Data.Entity.DbSet`1.Add(TEntity entity)\r\n at iisCMS.Controllers.GetAppsController.PostApp(App app)\r\n at lambda_method(Closure , Object , Object[])\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)"}
當我檢查從服務器的響應,這是application/xml
,我想我需要text/xml
任何方式轉換成一個到另一個?
從Logcat發佈您的日誌。 –
你確定你有這個xml解析嗎? –
你在'xml'中得到了什麼?顯然不是XML,因此請檢查響應是否不正確(200),但可能需要重定向(302)。 POST的URL是否正確?沒有GET?沒有參數? –