Java HttpResponse 提取数据

Posted

技术标签:

【中文标题】Java HttpResponse 提取数据【英文标题】:Java HttpResponse Extract data 【发布时间】:2021-12-23 11:36:26 【问题描述】:

我有一个 java 代码。此代码执行 http 请求并获得响应。响应返回了多个对象。我想创建一个 Map

的 ArrayList

每个地图实例将存储一个对象。我如何处理响应并存储在地图的数组列表中

这是我的代码

package com.mycompany.sfmc_test_kpmgnl;

import com.exacttarget.fuelsdk.ETSdkException;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Properties;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.soap.SOAPPart;
import org.apache.http.util.EntityUtils;

public class KPMG_Get_BusinessUnits 

    public static void main(String[] args) throws ETSdkException, FileNotFoundException, IOException, UnirestException, SOAPException 
        FileReader reader = new FileReader("D:\\Works\\Java\\SFMC_Test_KPMGNL\\src\\main\\java\\com\\mycompany\\sfmc_test_kpmgnl\\fuelsdk.properties");  
        Properties prop = new Properties();
        prop.load(reader);
        String TenentId = prop.getProperty("TenantId");
        
        SFMC_GetAccessToken Tokenclass = new SFMC_GetAccessToken();
        HashMap<String, Object> Token = Tokenclass.TokenInfo();
        String TokenValue = (String) Token.get("access_token");
        Integer Token_Expiry = (Integer) Token.get("expires_in");
        String token_type_value = (String) Token.get("token_type");
        String payload = get_BU_Payload(TokenValue,TenentId);
        Unirest.setTimeouts(0, 0);
        HttpResponse<String> response = Unirest.post("https://"+TenentId+".soap.marketingcloudapis.com/Service.asmx")
                .header("Content-Type", "text/xml")
                .header("Authorization", "Bearer"+TokenValue)
                .header("Action", "Retrieve")
                .body(payload).asString();
        
        if(response.getStatus()==200)
            //ArrayList<Map<String,String>> BU_Data = new ArrayList<Map<String,String>>();
            System.out.println(response.getBody());
              
        

    

    static String get_BU_Payload(String AccessToken,String TenentId) throws SOAPException, IOException 
        String BU_Payload = "";
        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage soapMsg = factory.createMessage();
        SOAPPart part = soapMsg.getSOAPPart();
        
        //Envelope
        SOAPEnvelope envelope = part.getEnvelope();
        envelope.setPrefix("s");
        envelope.addNamespaceDeclaration("a", "http://schemas.xmlsoap.org/ws/2004/08/addressing");
        envelope.addNamespaceDeclaration("u", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
        
        //Header
        SOAPHeader header = envelope.getHeader();
        header.setPrefix("s");                
        header.addChildElement("Action","a").addTextNode("Retrieve").setAttribute("s:mustUnderstand", "1");
        header.addChildElement("To","a").addTextNode("https://"+TenentId+".soap.marketingcloudapis.com/Service.asmx").setAttribute("s:mustUnderstand", "1");        
        header.addChildElement("fueloauth","a").addTextNode(AccessToken).setAttribute("xmlns", "http://exacttarget.com");
         
        //Body
        SOAPBody body = envelope.getBody();
        body.setPrefix("s");
        body.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
        body.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");         
        SOAPBodyElement Wrapper_Method_Element = (SOAPBodyElement) body.addChildElement("RetrieveRequestMsg","","http://exacttarget.com/wsdl/partnerAPI");        
        SOAPBodyElement Method_Element = (SOAPBodyElement) Wrapper_Method_Element.addChildElement("RetrieveRequest");
        Method_Element.addChildElement("ObjectType").addTextNode("BusinessUnit");
        Method_Element.addChildElement("QueryAllAccounts").addTextNode("true");
        Method_Element.addChildElement("Properties").addTextNode("Name");
        Method_Element.addChildElement("Properties").addTextNode("AccountType");
        Method_Element.addChildElement("Properties").addTextNode("BusinessName");
        Method_Element.addChildElement("Properties").addTextNode("ParentID");
        Method_Element.addChildElement("Properties").addTextNode("CustomerKey");
        Method_Element.addChildElement("Properties").addTextNode("EditionID");
        Method_Element.addChildElement("Properties").addTextNode("FromName");
        Method_Element.addChildElement("Properties").addTextNode("ID");

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        soapMsg.writeTo(stream);
        BU_Payload = new String(stream.toByteArray(), "utf-8") ;
        return BU_Payload;
    

我收到的回复

<?xml version="1.0" encoding="UTF-8"?>
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
       <soap:Header>
          <wsa:Action>RetrieveResponse</wsa:Action>
          <wsa:MessageID>urn:uuid:533e4809-2358-4302-b7f4-65d27107fc9b</wsa:MessageID>
          <wsa:RelatesTo>urn:uuid:956a1c31-85e6-4a31-8722-bdb215764ad6</wsa:RelatesTo>
          <wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To>
          <wsse:Security>
             <wsu:Timestamp wsu:Id="Timestamp-745764aa-1012-40ed-853e-99576a471b4c">
                <wsu:Created>2021-11-10T20:56:21Z</wsu:Created>
                <wsu:Expires>2021-11-10T21:01:21Z</wsu:Expires>
             </wsu:Timestamp>
          </wsse:Security>
       </soap:Header>
       <soap:Body>
          <RetrieveResponseMsg xmlns="http://exacttarget.com/wsdl/partnerAPI">
             <OverallStatus>OK</OverallStatus>
             <RequestID>9b218589-3484-4ee5-9386-098449b30061</RequestID>
             <Results xsi:type="BusinessUnit">
                <PartnerKey xsi:nil="true" />
                <ID>510004255</ID>
                <ObjectID xsi:nil="true" />
                <CustomerKey>ffsdfsfdsf</CustomerKey>
                <AccountType>ENTERPRISE_2</AccountType>
                <ParentID>0</ParentID>
                <Name>KPMG N.V.</Name>
                <FromName>KPMG N.V.</FromName>
                <BusinessName>KPMG N.V.</BusinessName>
                <EditionID>32</EditionID>
                <Subscription xsi:nil="true" />
             </Results>
             <Results xsi:type="BusinessUnit">
                <PartnerKey xsi:nil="true" />
                <ID>510004263</ID>
                <ObjectID xsi:nil="true" />
                <CustomerKey>gfdhfghgf</CustomerKey>
                <AccountType>BUSINESS_UNIT</AccountType>
                <ParentID>510004255</ParentID>
                <Name>Shekhar</Name>
                <FromName>Shekhar Dautpure</FromName>
                <BusinessName>KPMG N.V.</BusinessName>
                <EditionID>0</EditionID>
                <Subscription xsi:nil="true" />
             </Results>
             <Results xsi:type="BusinessUnit">
                <PartnerKey xsi:nil="true" />
                <ID>510004264</ID>
                <ObjectID xsi:nil="true" />
                <CustomerKey>vcbcvcvbvcb</CustomerKey>
                <AccountType>BUSINESS_UNIT</AccountType>
                <ParentID>510004255</ParentID>
                <Name>Jeroen</Name>
                <FromName>Jeroen Haster</FromName>
                <BusinessName>KPMG N.V.</BusinessName>
                <EditionID>0</EditionID>
                <Subscription xsi:nil="true" />
             </Results>
             <Results xsi:type="BusinessUnit">
                <PartnerKey xsi:nil="true" />
                <ID>510004265</ID>
                <ObjectID xsi:nil="true" />
                <CustomerKey>hfghfghgf</CustomerKey>
                <AccountType>BUSINESS_UNIT</AccountType>
                <ParentID>510004255</ParentID>
                <Name>Kemal</Name>
                <FromName>Kemal Falatehan</FromName>
                <BusinessName>KPMG N.V.</BusinessName>
                <EditionID>0</EditionID>
                <Subscription xsi:nil="true" />
             </Results>
             <Results xsi:type="BusinessUnit">
                <PartnerKey xsi:nil="true" />
                <ID>510004267</ID>
                <ObjectID xsi:nil="true" />
                <CustomerKey>dfhfghgfh</CustomerKey>
                <AccountType>BUSINESS_UNIT</AccountType>
                <ParentID>510004255</ParentID>
                <Name>Faysal</Name>
                <FromName>Faysal Mataich</FromName>
                <BusinessName>KPMG N.V.</BusinessName>
                <EditionID>0</EditionID>
                <Subscription xsi:nil="true" />
             </Results>
             <Results xsi:type="BusinessUnit">
                <PartnerKey xsi:nil="true" />
                <ID>510004269</ID>
                <ObjectID xsi:nil="true" />
                <CustomerKey>fgfgjgjghjhg</CustomerKey>
                <AccountType>BUSINESS_UNIT</AccountType>
                <ParentID>510004255</ParentID>
                <Name>Training</Name>
                <FromName>Shekhar Dautpure</FromName>
                <BusinessName>KPMG N.V.</BusinessName>
                <EditionID>0</EditionID>
                <Subscription xsi:nil="true" />
             </Results>
             <Results xsi:type="BusinessUnit">
                <PartnerKey xsi:nil="true" />
                <ID>510004891</ID>
                <ObjectID xsi:nil="true" />
                <CustomerKey>dgfhfghfghgfhgf</CustomerKey>
                <AccountType>BUSINESS_UNIT</AccountType>
                <ParentID>510004255</ParentID>
                <Name>SG_DEMO</Name>
                <FromName>KPMG Singapore</FromName>
                <BusinessName>KPMG Singapore</BusinessName>
                <EditionID>0</EditionID>
                <Subscription xsi:nil="true" />
             </Results>
             <Results xsi:type="BusinessUnit">
                <PartnerKey xsi:nil="true" />
                <ID>510005831</ID>
                <ObjectID xsi:nil="true" />
                <CustomerKey>fddffdghfghgf</CustomerKey>
                <AccountType>BUSINESS_UNIT</AccountType>
                <ParentID>510004255</ParentID>
                <Name>Ivor</Name>
                <FromName>Ivor</FromName>
                <BusinessName>KPMG N.V.</BusinessName>
                <EditionID>0</EditionID>
                <Subscription xsi:nil="true" />
             </Results>
             <Results xsi:type="BusinessUnit">
                <PartnerKey xsi:nil="true" />
                <ID>510005853</ID>
                <ObjectID xsi:nil="true" />
                <CustomerKey>cvbbnbghnm</CustomerKey>
                <AccountType>BUSINESS_UNIT</AccountType>
                <ParentID>510004255</ParentID>
                <Name>Jurrien Vermolen</Name>
                <FromName>Jurrien Vermolen</FromName>
                <BusinessName>KPMG N.V.</BusinessName>
                <EditionID>0</EditionID>
                <Subscription xsi:nil="true" />
             </Results>
             <Results xsi:type="BusinessUnit">
                <PartnerKey xsi:nil="true" />
                <ID>510005854</ID>
                <ObjectID xsi:nil="true" />
                <CustomerKey>fghfgfghfggfh</CustomerKey>
                <AccountType>BUSINESS_UNIT</AccountType>
                <ParentID>510004255</ParentID>
                <Name>David van Daalen</Name>
                <FromName>David van Daalen</FromName>
                <BusinessName>KPMG N.V.</BusinessName>
                <EditionID>0</EditionID>
                <Subscription xsi:nil="true" />
             </Results>
             <Results xsi:type="BusinessUnit">
                <PartnerKey xsi:nil="true" />
                <ID>510005855</ID>
                <ObjectID xsi:nil="true" />
                <CustomerKey>fdgdgdfgdfgfdg</CustomerKey>
                <AccountType>BUSINESS_UNIT</AccountType>
                <ParentID>510004255</ParentID>
                <Name>Jeroen Slijkerman</Name>
                <FromName>Jeroen Slijkerman</FromName>
                <BusinessName>KPMG N.V.</BusinessName>
                <EditionID>0</EditionID>
                <Subscription xsi:nil="true" />
             </Results>
             <Results xsi:type="BusinessUnit">
                <PartnerKey xsi:nil="true" />
                <ID>510005856</ID>
                <ObjectID xsi:nil="true" />
                <CustomerKey>dfgdfgdfgdfgfdgfd</CustomerKey>
                <AccountType>BUSINESS_UNIT</AccountType>
                <ParentID>510004255</ParentID>
                <Name>Kay van der Vleuten</Name>
                <FromName>Kay van der Vleuten</FromName>
                <BusinessName>KPMG N.V.</BusinessName>
                <EditionID>0</EditionID>
                <Subscription xsi:nil="true" />
             </Results>
             <Results xsi:type="BusinessUnit">
                <PartnerKey xsi:nil="true" />
                <ID>510005857</ID>
                <ObjectID xsi:nil="true" />
                <CustomerKey>fdfgfdgfdgfdg</CustomerKey>
                <AccountType>BUSINESS_UNIT</AccountType>
                <ParentID>510004255</ParentID>
                <Name>Kim van Kaam</Name>
                <FromName>Kim van Kaam</FromName>
                <BusinessName>KPMG N.V.</BusinessName>
                <EditionID>0</EditionID>
                <Subscription xsi:nil="true" />
             </Results>
          </RetrieveResponseMsg>
       </soap:Body>
    </soap:Envelope>

我想将每个“结果”映射到一张地图。所以在这种情况下 ArrayList 将包含 13 个地图。第一张地图将是 地图1 "ID":"510004255", "客户密钥":"ffsdfsfdsf" ...

我应该如何处理响应以创建这样的地图列表

【问题讨论】:

【参考方案1】:

我能够使用文档构建器和解析响应正文来解决问题。

if(response.getStatus()==200)
            ArrayList<Map<String,String>> BU_Data = new ArrayList<Map<String,String>>();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newDefaultInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document res = builder.parse(new InputSource(new StringReader(response.getBody())));
            NodeList resultList = res.getElementsByTagName("Results");
            for(int i=0;i<resultList.getLength();i++)
                Node p = resultList.item(i);
                if(p.getNodeType()==Node.ELEMENT_NODE)
                    Element BU_Info = (Element) p;
                    NodeList ResultList = BU_Info.getChildNodes();
                    for(int j=0;j<ResultList.getLength();j++)
                        Node n = ResultList.item(j);
                        if(n.getNodeType()==Node.ELEMENT_NODE)
                            Element Result_Value = (Element) n;
                            System.out.println(Result_Value.getTagName()+" "+Result_Value.getTextContent());
                        
                    
                
                System.out.println("------------------");
                        
         

一个重要的事情是builder.parse。它需要一个 Inputsource 和字符串阅读器。如果你不使用它,你可能会得到格式错误的 URL 异常

【讨论】:

以上是关于Java HttpResponse 提取数据的主要内容,如果未能解决你的问题,请参考以下文章

在Java 8中,如果map具有重复值,则会出现重复值异常

如何从 Java 中的 HttpResponse 中获取单个表单字段并将其写入文件?

PC 上的 Android 与 Java:不同的 HttpResponse?

Python 3 urllib json AttributeError:“HTTPResponse”对象没有属性“type”

如何从 Java HTTPResponse 解析 JSON?

在Java中怎样得到一个HttpResponse对象