2012-03-14 66 views
1

我需要在android中使用http post發送一個xml文件。我是新來的。我在哪裏把xml放在android中,以及如何使用代碼發送它。如何在android中使用http post發送xml文件。我在哪裏把xml文件放在代碼中

的XML的樣品看起來像這樣

http://api.ean.com/ean-services/rs/hotel/v3/list? 
    minorRev=[current minorRev #] 
    &cid=55505 
    &apiKey=[xxx-yourOwnKey-xxx] 
    &customerUserAgent=[xxx] 
    &customerIpAddress=[xxx] 
    &locale=en_US 
    &currencyCode=USD 
    &xml= 
    <HotelListRequest> 
    <city>Seattle</city> 
    <stateProvinceCode>WA</stateProvinceCode> 
    <countryCode>US</countryCode> 
    <arrivalDate>08/01/2012</arrivalDate> 
    <departureDate>08/03/2012</departureDate> 
    <RoomGroup> 
    <Room> 
    <numberOfAdults>2</numberOfAdults> 
    </Room> 
    </RoomGroup> 
    <numberOfResults>1</numberOfResults> 
     <supplierCacheTolerance>MED_ENHANCED</supplierCacheTolerance> 
     </HotelListRequest> 

回答

3

創建XML文件

DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); 
dbfac.setNamespaceAware(true); 
DocumentBuilder docBuilder = null; 
try { 
    docBuilder = dbfac.newDocumentBuilder(); 
} catch (ParserConfigurationException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 
DOMImplementation domImpl = docBuilder.getDOMImplementation(); 
Document doc = domImpl.createDocument("http://coggl.com/InsertTrack","TrackEntry", null); 
doc.setXmlVersion("1.0"); 
doc.setXmlStandalone(true); 

Element trackElement = doc.getDocumentElement(); 

Element CompanyId = doc.createElement("CompanyId"); 
CompanyId.appendChild(doc.createTextNode("1")); 
trackElement.appendChild(CompanyId); 

Element CreatedBy = doc.createElement("CreatedBy"); 
CreatedBy.appendChild(doc.createTextNode("6")); 
trackElement.appendChild(CreatedBy); 

Element DepartmentId = doc.createElement("DepartmentId"); 
DepartmentId.appendChild(doc.createTextNode("4")); 
trackElement.appendChild(DepartmentId); 

Element IsBillable = doc.createElement("IsBillable"); 
IsBillable.appendChild(doc.createTextNode("1")); 
trackElement.appendChild(IsBillable); 

Element ProjectId = doc.createElement("ProjectId"); 
ProjectId.appendChild(doc.createTextNode("1")); 
trackElement.appendChild(ProjectId); 

Element StartTime = doc.createElement("StartTime"); 
StartTime.appendChild(doc.createTextNode("2012-03-14 10:44:45")); 
trackElement.appendChild(StartTime); 

Element StopTime = doc.createElement("StopTime"); 
StopTime.appendChild(doc.createTextNode("2012-03-14 11:44:45")); 
trackElement.appendChild(StopTime); 

Element TaskId = doc.createElement("TaskId"); 
TaskId.appendChild(doc.createTextNode("3")); 
trackElement.appendChild(TaskId); 

Element TotalTime = doc.createElement("TotalTime"); 
TotalTime.appendChild(doc.createTextNode("1")); 
trackElement.appendChild(TotalTime); 

Element TrackDesc = doc.createElement("TrackDesc"); 
TrackDesc.appendChild(doc.createTextNode("dello testing")); 
trackElement.appendChild(TrackDesc); 

Element TrackId = doc.createElement("TrackId"); 
TrackId.appendChild(doc.createTextNode("0")); 
trackElement.appendChild(TrackId); 

TransformerFactory transfac = TransformerFactory.newInstance(); 
Transformer trans = null; 
try { 
    trans = transfac.newTransformer(); 
} catch (TransformerConfigurationException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); 
trans.setOutputProperty(OutputKeys.INDENT, "yes"); 

//create string from xml tree 
StringWriter sw = new StringWriter(); 
StreamResult result = new StreamResult(sw); 
DOMSource source = new DOMSource(doc); 
try { 
    trans.transform(source, result); 
} catch (TransformerException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 
String xmlString = sw.toString(); 

//posting xml file to server 

DefaultHttpClient httpClient = new DefaultHttpClient(); 

HttpPost httppost = new HttpPost("http://192.168.0.19:3334/cogglrestservice.svc/InsertTrack");  
// Make sure the server knows what kind of a response we will accept 
httppost.addHeader("Accept", "text/xml"); 
// Also be sure to tell the server what kind of content we are sending 
httppost.addHeader("Content-Type", "application/xml"); 

try 
{ 
StringEntity entity = new StringEntity(xmlString, "UTF-8"); 
entity.setContentType("application/xml"); 
httppost.setEntity(entity); 

// execute is a blocking call, it's best to call this code in a thread separate from the ui's 
HttpResponse response = httpClient.execute(httppost); 

BasicResponseHandler responseHandler = new BasicResponseHandler(); 
    String strResponse = null; 
    if (response != null) { 
     try { 
      strResponse = responseHandler.handleResponse(response); 
     } catch (HttpResponseException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    Log.e("WCFTEST", "WCFTEST ********** Response" + strResponse);  


} 
catch (Exception ex) 
{ 
ex.printStackTrace(); 
} 
Toast.makeText(EditTask.this, "Xml posted succesfully.",Toast.LENGTH_SHORT).show(); 
+0

如何iclude此xml在StringEntity XML&XML = 西雅圖 WA US 08月01日 08/03/2012 2 1 <與供應rCacheTolerance> MED_ENHANCED vinuonline 2012-03-21 10:34:14

+0

我剛剛找到了這個解決方案,它似乎在爲我工作。但是,strResponse變量在成功連接時始終爲空?我還需要能夠看到服務器觸發的實際響應(我的APi啓動了一個XML塊)。我怎樣才能看到這個? – 2013-06-03 10:54:03

+0

@PradeepSodhi我如何將它作爲get參數發送並檢查XML響應 – onkar 2014-03-20 13:17:44

1
HttpPost httpPost = new HttpPost("Your target Url"); 
httpPost.addHeader("Content-Type", "application/xml"); 

StringEntity entity = new StringEntity("<input>test</input>", "UTF-8"); 
entity.setContentType("application/xml"); 
httpPost.setEntity(entity); 

HttpHost targetHost = new HttpHost("targetDomain", 80, "http"); 
HttpResponse response = httpClient.execute(targetHost, httpPost); 
+0

感謝各位的回覆@ sadeshkumar-periyasamy – vinuonline 2012-03-14 04:56:10

+0

targethost與targetDomain什麼是的,httpClient的聲明在哪裏? – deadfish 2013-08-28 16:20:38

0
  DefaultHttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost("http://foo/service1.asmx/GetUID");  


        //XML example to send via Web Service. 
      StringBuilder sb = new StringBuilder(); 
      sb.append("<myXML><Parametro><name>IdApp</name><value>1234567890</value></Parameter>"); 
      sb.append("<Parameter><name>UID1</name><value>abc12421</value></Parameter>"); 
        sb.append("</myXML>"); 

      httppost.addHeader("Accept", "text/xml"); 
      httppost.addHeader("Content-Type", "application/x-www-form-urlencoded"); 

      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
      nameValuePairs.add(new BasicNameValuePair("myxml", sb.toString());//WS Parameter and Value   
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
      HttpResponse response = httpclient.execute(httppost);