2012-07-20 7 views
0

Android 활동 내에서 HTTP POST 요청을하고 싶습니다. 나는 그렇게 할 수있는 방법을 안다.하지만 내 문제는 XML 파일을 만드는 방법을 모른다. 이전 게시물에서 설명한 여러 가지 방법을 시도했지만 그렇게 할 수 없었습니다.HTTP POST 요청 XML 생성

내 XML 형식은 다음

나는 다음과 같은 자바 코드 라인을 작성했습니다
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>  
<IAM version="1.0"> 
    <ServiceRequest> 
     <RequestTimestamp>2012-07-20T11:10:12Z</RequestTimestamp 
     <RequestorRef>username</RequestorRef> 
     <StopMonitoringRequest version="1.0"> 
      <RequestTimestamp>2012-07-20T11:10:12Z</RequestTimestamp> 
      <MessageIdentifier>12345</MessageIdentifier> 
      <MonitoringRef>112345</MonitoringRef> 
     </StopMonitoringRequest> 
    </ServiceRequest> 
</IAM> 

: 어떻게 든 사용하여 XML을 생성하는 데 성공하지만

DefaultHttpClient httpClient = new DefaultHttpClient(); 
HttpPost httpPost = new HttpPost(url); 

//What to write here to add the above XML lines? 

HttpResponse httpResponse = httpClient.execute(httpPost); 
HttpEntity httpEntity = httpResponse.getEntity(); 
xml = EntityUtils.toString(httpEntity); 

편집

다음과 같은 결과가 나왔습니다.

StringBuilder sb = new StringBuilder(); 
sb.append("<?xml version='1.0' encoding='UTF-8' standalone='yes'?>"); 
sb.append("<IAM version'1.0'>"); 
sb.append("<ServiceRequest>"); 
sb.append("<RequestTimestamp>2012-07-20T12:33:00Z</RequestTimestamp"); 
sb.append("<RequestorRef>username</RequestorRef>"); 
sb.append("<StopMonitoringRequest version='1.0'>"); 
sb.append("<RequestTimestamp>2012-07-20T12:33:00Z</RequestTimestamp>"); 
sb.append("<MessageIdentifier>12345</MessageIdentifier>"); 
sb.append("<MonitoringRef>32900109</MonitoringRef>"); 
sb.append("</StopMonitoringRequest>"); 
sb.append("</ServiceRequest>"); 
sb.append("</IAM>"); 
String xmlContentTosend = sb.toString(); 

StringEntity entity = new StringEntity(xmlContentTosend, "UTF-8"); 
httpPost.setEntity(entity); 
httpPost.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials("username", "password"), "UTF-8", false)); 

HttpResponse httpResponse = httpClient.execute(httpPost); 
HttpEntity httpEntity = httpResponse.getEntity(); 
xml = EntityUtils.toString(httpEntity); 

나는 전체 응답이 아닌 String 파일 (xml)을 가져 왔습니다. 파이어 폭스의 HTTP 리소스 테스트를 사용할 경우 정답을 얻는 반면 내 솔루션에서는 부분적인 답변을 얻습니다. 나는

<IAM version="1.0"> 

라인이나 (은 XML의 구조를 "파괴"일반적으로) 다른 라인을 제거 할 때 나는 HTTP 자원 테스트에서 같은 부분적인 답을받을 수 있었다. 그러나 그것이 관련이 있는지 나는 모른다.

EDIT (솔루션 발견) 찾을 수 있습니까? xml 구조의 첫 번째 RequestTimestamp에 누락 된 ">"이 있습니다. 나는 그것을 하루 종일 붙이기 때문에 나는 그것을 언급하지 않았다. 풋 ...

+0

응답 내용은 무엇입니까? –

+0

마지막으로 EDIT를 확인하십시오. – Thanos

답변

4

당신은 DOM 파서 여기

를 사용하여이 개입시켜 보내는 것이

<?xml version="1.0" encoding="UTF-8" standalone="no" ?> 
<company> 
    <staff id="1"> 
     <firstname>yong</firstname> 
     <lastname>mook kim</lastname> 
     <nickname>mkyong</nickname> 
     <salary>100000</salary> 
    </staff> 
</company> 

Source.

같은 XML을 생성하는 코드

public class WriteXMLFile { 

    public static void main(String argv[]) { 

     try { 

     DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); 

     // root elements 
     Document doc = docBuilder.newDocument(); 
     Element rootElement = doc.createElement("company"); 
     doc.appendChild(rootElement); 

     // staff elements 
     Element staff = doc.createElement("Staff"); 
     rootElement.appendChild(staff); 

     // set attribute to staff element 
     Attr attr = doc.createAttribute("id"); 
     attr.setValue("1"); 
     staff.setAttributeNode(attr); 

     // shorten way 
     // staff.setAttribute("id", "1"); 

     // firstname elements 
     Element firstname = doc.createElement("firstname"); 
     firstname.appendChild(doc.createTextNode("yong")); 
     staff.appendChild(firstname); 

     // lastname elements 
     Element lastname = doc.createElement("lastname"); 
     lastname.appendChild(doc.createTextNode("mook kim")); 
     staff.appendChild(lastname); 

     // nickname elements 
     Element nickname = doc.createElement("nickname"); 
     nickname.appendChild(doc.createTextNode("mkyong")); 
     staff.appendChild(nickname); 

     // salary elements 
     Element salary = doc.createElement("salary"); 
     salary.appendChild(doc.createTextNode("100000")); 
     staff.appendChild(salary); 

     // write the content into xml file 
     TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
     Transformer transformer = transformerFactory.newTransformer(); 
     DOMSource source = new DOMSource(doc); 
     StreamResult result = new StreamResult(new File("C:\\file.xml")); 

     // Output to console for testing 
     // StreamResult result = new StreamResult(System.out); 

     transformer.transform(source, result); 

     System.out.println("File saved!"); 

     } catch (ParserConfigurationException pce) { 
     pce.printStackTrace(); 
     } catch (TransformerException tfe) { 
     tfe.printStackTrace(); 
     } 
    } 
} 

가 있다고 할 수있다 http 게시물 :

HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://192.168.192.131/"); 

    try { 
     StringEntity se = new StringEntity("<aaaLogin inName=\"admin\" inPassword=\"admin123\"/>", HTTP.UTF_8); 
     se.setContentType("text/xml"); 
     httppost.setEntity(se); 

     HttpResponse httpresponse = httpclient.execute(httppost); 
     HttpEntity resEntity = httpresponse.getEntity(); 
     tvData.setText(EntityUtils.toString(resEntity)); 

    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

및 btw와 같이 XML 대신 JSON을 사용하는 것이 좋습니다. 더 효율적이고 사용하기 쉽습니다.

+0

요청을 보내는 서버가 내 것이 아닙니다. 내가 아는 한 그들은 XML만을 받아 들인다. – Thanos

+0

좋습니다, 문서를 만들었습니다. httpPost에 추가 할 엔터티를 어떻게 만들 수 있습니까? – Thanos

+0

수정 사항을 참조하십시오 ... –