2015-02-05 2 views
1

원래 요청이 xml 인 Restful WS에 POST 요청을 보내려고하므로 응답도 마찬가지입니다.Groovy httpBuilder 기본 인증을 사용하는 POST XML

기본 인증도 보내야합니다. 처음에는 Classes와 관련하여 문제가 발생하지 않았으며 고맙게도 해결하기 위해 6 개의 항아리가 필요했습니다. 잘못된 요청이 POST 요청을 좋아하지 않는처럼

는 소리 : 잡았다 : groovyx.net.http.HttpResponseException

는 이제 다음을 점점 계속. RESTClient를 포함하여 여러 가지 방법을 시도해 봤지만 파일을 전달하거나 문자열 var로 원시 xml 형식으로 요청을 위임하려고했습니다. httpBuilder에서 게시 또는 요청 방법의 차이를 완전히 이해하지 못했습니다.

:

사람이 내가 잘못

def http = new HTTPBuilder('http://some_IP:some_Port/') 
http.auth.basic('userName','password') 
http.post(path:'/path/ToServlet') 

http.post(POST,XML) 
{ 

    delegate.contentType="text/xml" 
    delegate.headers['Content-Type']="text/xml" 
    //delegate.post(getClass().getResource("/query.xml")) 
// body = getClass().getResource("/query.xml") 
    body = 
    { 
     mkp.xmlDeclaration() 

     Request{ 
      Header{ 
        Command('Retrieve') 
        EntityIdentifiers 
        { 
         Identifier(Value:'PhoneNumber', Type:'TelephoneNumber') 
         } 
            EntityName('Subscriber') 
        } 
     } 
    } 
} 

지금 경우에 내가 여기 내 요청에 잘못된 XML을 번역

매우 감사 할 것입니다 무슨 짓을했는지 날 지점 도움이 될 수 있다면 그것의 XML 버전입니다
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<Provisioning xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
<Request> 
    <Header> 
     <Command>Retrieve</Command> 
     <EntityIdentifiers> 
      <Identifier Value="phoneNumber" Type="TelephoneNumber" /> 
     </EntityIdentifiers> 
     <EntityName>Subscriber</EntityName> 
    </Header> 
</Request> 
</Provisioning> 

답변

1

좋아 언젠가 후에 나는 솔루션과 httpClient4.0.1 및 httpBuilder가 4.x를 보인다

가 I로 트릭을 수행 한 것으로 2.4에 끝내 라이브러리를 업그레이드 있었다 모여 있도록 원래 groovy 1.5.5와 함께 일하고있다 다른 옵션은 Java와 Groovy를 함께 사용하여 URL과 HttpURLConnection 클래스를 사용하여 연결을 설정하는 것입니다. 거기에 충분한 예제가 있기를 바랍니다. 이 SSL이 아닌 것을 염두해야합니다 하고

import groovy.xml.* 
import groovy.util.XmlSlurper.* 
import groovy.util.slurpersupport.GPathResult.* 


import groovyx.net.http.HTTPBuilder 

import groovyx.net.http.EncoderRegistry 
import java.net.URLEncoder 
import java.net.URLEncoder.* 
import org.apache.http.client.* 
import org.apache.http.client.HttpResponseException 
import org.apache.http.protocol.ResponseConnControl; 
import org.apache.http.conn.ssl.* 
import org.apache.http.conn.ssl.TrustStrategy 

import static java.net.URLEncoder.encode 
import static groovyx.net.http.ContentType.* 
import static groovyx.net.http.HTTPBuilder.request 
import static groovyx.net.http.Method.POST 
//import static groovyx.net.http.RESTClient.* 


def SMSCmirrorServerTor = "http://IP:PORT" 
def SMSCmirrorServerMntrl = "http://IP:PORT" 


def msisdn = args[0] 

//Connect to method HTTP xml URL encoded request, XML response 
def connectSMSC(server, MSISDN) 
{ 
    // Variables used for the response 
    def result = "" 
    //Variables used for request 
    // one way is to use raw xml 
    def rawXML = """ 
    <Provisioning xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'> 
      <Request> 
        <Header> 
          make sure your <xml> is well formatted use xml formatter online if need be 
        </Header> 
      </Request> 
    </Provisioning>""" 

    def http = new HTTPBuilder(server) 
    http.auth.basic('username','password') 
    http.contentType = TEXT 
    http.headers = [Accept: 'application/xml', charset: 'UTF-8'] 

    http.request(POST) 
    { 
     uri.path = 'Servlet or WS/Path' 
     requestContentType = URLENC 
     body = "provRequest=" + encode(rawXML,"UTF-8") 


     response.success = { resp, xml -> 

     def xmlParser = new XmlSlurper().parse(xml) 
     //Helps if you know in advance the XML response tree structure at this point it's only xmlSlurper doing the work to parse your xml response 
     def ResponseStatus = xmlParser.Response.Header.ResponseStatus 
     result += "Response Status: " + ResponseStatus.toString() + "\n================\n" 

     def ResponseHeader = xmlParser.Response.Header.Errors.Error 
     ResponseHeader.children().each 
     { 
      result += "\n${it.name()}: " + it.text().toString() + "\n" 

     } 

     def xmlDataRootNode = xmlParser.Response.Data.Subscriber 
     xmlDataRootNode.children().each 
     { 

      if (it.name() == 'UserDevices') 
      { 
      result += "\n" + it.UserDevice.name() + " :" + "\n-----------------\n" 
      it.UserDevice.children().each 
      { 
       result += it.name() + " :" + it.text().toString() + "\n" 
      } 
      } 
      else 
      { 
      result += "\n${it.name()}: " + it.text().toString() + "\n" 
      } 

     }//End of each iterator on childNodes 

     if (ResponseStatus.text().toString() == "Failure") 
     { 
      def ErrorCode = resp.status 
      result += "Failed to process command. Bad request or wrong input" 
      //result += "\nHTTP Server returned error code: " + ErrorCode.toString() 
      // Note this error is for bad input server will still return status code 200 meaning o.k. unlike err 401 unathorized or err 500 those are http errors so be mindful of which error handling we're talking about here application layer vs http protocol layer error handling 
     } 

     }//End of response.success closure 
    }//End of http.request(POST) method 

    result 
}//end of connectSMSC method 


//the following is only in case server A is down we can try server B 
def finalResponse="" 
try 
{ 
    finalResponse += connectSMSC(SMSCmirrorServerTor,msisdn) 

} 

catch(org.apache.http.conn.HttpHostConnectException e) 
{ 

    finalResponse += "Encountered HTTP Connection Error\n ${e}\n Unable to connect to host ${SMSCmirrorServerTor}\n Trying to connect to mirror server ${SMSCmirrorServerMntrl} instead\n" 
    finalResponse += connectSMSC(SMSCmirrorServerMntrl,msisdn) 
} 
catch (groovyx.net.http.HttpResponseException ex) 
{ 

    finalResponse += "Encountered HTTP Connection Error Code: ${ex.statusCode}\n" 
    finalResponse += connectSMSC(SMSCmirrorServerMntrl,msisdn) 
} 
/* 
* 
* java.lang.IllegalArgumentException: port out of range: 

*/ 
catch(java.lang.IllegalArgumentException e) 
{ 
finalResponse += "Error: " + e 
} 

catch(java.io.IOException e) 
{ 

    finalResponse += "IO Error: " + e 
    finalResponse += connectSMSC(SMSCmirrorServerMntrl,msisdn) 
} 
catch(java.io.FileNotFoundException e) 
{ 

    finalResponse += "IO Error: " + e 
    finalResponse += connectSMSC(SMSCmirrorServerMntrl,msisdn) 
} 


println finalResponse.toString() 
0

요청을 게시하려는 것처럼 보이지 않으며 어느 쪽도 올바르게 구성되지 않았습니다. 이런 식으로 뭔가를 시도 :

def writer = new StringWriter() 

def req = new MarkupBuilder(writer) 
req.mkp.xmlDeclaration(version:"1.0", encoding:"utf-8") 
req.Provisioning { 
    Request { 
     Header { 
      Command('Retrieve') 
      EntityIdentifiers { 
       Identifier(Value:'PhoneNumber', Type:'TelephoneNumber') 
      } 
      EntityName('Subscriber') 
     } 
    } 
} 

def http = new HTTPBuilder('http://some_IP:some_Port/path/ToServlet') 
http.auth.basic('userName','password') 
http.post(contentType:XML, query:writer) { resp, xml -> 
    // do something with response 
} 
+0

당신이 그것을 지금은 실제로 잘 볼 수있는 조금 더 나은 것 같다 을 @MichaelRutherford 감사 SSL 및 https로이 작업을 수행하려면 추가 단계를 수행해야 할 수 있습니다 형식화 된 XML 요청 그러나 HTTPBuilder가 호환되는 인수 유형에 대해 불평합니다. 명령 행에서 groovy 스크립트를 실행할 때 다음과 같은 오류가 발생합니다. java.io.StringWriter를 java.util.Map – user3849802

+0

으로 캐스팅 할 수없고 Eclipse에서이 오류가 발생합니다. 어떤 종류의 이클립스 버그가있는 groovyx.net이라고합니다 : 메소드의 서명이 없습니다 : groovyx.net.http.HTTPBuilder.post() (java.util.LinkedHashMap, SMSC $ _run_closure2) 값 : {[ "contentType": application/xml, "query": @Michael Rutherfurd – user3849802

+0

groovy.xml.MarkupBuilder는 java.util.Map으로 캐스트 할 수 없습니다. 캐스팅 오류가 발생합니다. Map 또는 LinkedHashMap from xml.MarkupBuilder 올바른 유형으로 캐스트하는 방법 !! – user3849802