http解析异常apollo Graphql

问题描述 投票:0回答:1

我在使用Apollo GraphQL Client for Android时遇到了http解析异常,但是当我使用HttpLoggingInterceptor进行调试时,我能够看到状态码为200的json数据

任何人都解决了这个问题?

下面是调用graphql查询的方法

private void getData(){

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor()
                                    .setLevel(HttpLoggingInterceptor.Level.BODY);

OkHttpClient httpClient = new OkHttpClient.Builder()
                        .addInterceptor(interceptor)
                        .build();

ApolloClient apolloClient = ApolloClient.builder()
                            .serverUrl(UrlUtils.GRAPHQL_URL)
                            .okHttpClient(httpClient)
                            .build();

apolloClient.query(DataQuery.builder().updated_at("0").build())
            .enqueue(new ApolloCall.Callback<DataQuery.Data>() {
                    @Override
                    public void onResponse(@Nonnull Response<DataQuery.Data> response) {
                            Log.d(Utils.CYBERBYTES_LOG,response.data().cyberNews().toString());
                    }

                    @Override
                    public void onFailure(@Nonnull ApolloException e) {
                        Log.d(Utils.CYBERBYTES_LOG,"Exception "+e.toString());
                    }
});
}

下面是apollo客户端中使用的graphql查询

query DataQuery($updated_at: String!){
  cyberNews (updated_at:$updated_at){
    _id
    heading
    description
    image
    created_at
  }
  cyberAlerts(updated_at:$updated_at) {
    _id
    title
    description
    created_at
  }
  afnetSecurity(updated_at:$updated_at) {
    _id
    heading
    description
    image
    created_at
  }
  internetSecurity(updated_at:$updated_at) {
    _id
    heading
    description
    image
    created_at
  }
  cyberToons(updated_at:$updated_at) {
    _id
    title
    video
    image
    created_at
  }
  cyberCases(updated_at:$updated_at) {
    _id
    title
    file
    created_at
  }
  certContacts(updated_at:$updated_at) {
    _id
    details
    created_at
  }
}

OnFailure回调被调用,我得到http

ApolloParseException: Failed to parse http response

但我能够在HttpLoggingInterceptor中看到所需的json数据

我使用依赖com.apollographql.apollo:apollo-runtime:1.0.0-alpha2

logcat的

09-05 09:31:23.594 6611-6611/cert.iaf.in.certindia D/CERTBYTES_LOG: Before Network Check
09-05 09:31:23.604 6611-6611/cert.iaf.in.certindia D/CERTBYTES_LOG: Get Graphql data
    URL: http://172.20.10.4:3000/graphql
09-05 09:31:23.744 6611-6611/cert.iaf.in.certindia D/ViewRootImpl: #1 mView = com.android.internal.policy.PhoneWindow$DecorView{f3d4712 I.E...... R.....ID 0,0-0,0}
09-05 09:31:23.754 1682-2188/? D/ActivityManager: post active user change for 0 fullscreen true isFloatingActivity() false isHomeActivity() false
09-05 09:31:23.754 1682-2188/? D/KnoxTimeoutHandler: postActiveUserChange [MsgParam] userId: 0 fullscreen is true showWhenlocked is false
09-05 09:31:23.754 1682-1682/? D/KnoxTimeoutHandler: handleActiveUserChange [MsgParam] userId: 0 fullscreen is true showWhenlocked is false
09-05 09:31:23.754 1682-1682/? I/KnoxTimeoutHandler: Shared devices show user statefalse
09-05 09:31:23.774 6611-6611/cert.iaf.in.certindia D/ViewRootImpl: #3 mView = null
09-05 09:31:23.794 340-340/? I/SurfaceFlinger: id=622 createSurf (720x1280),1 flag=404, Eashboard
09-05 09:31:23.794 1682-1866/? D/StatusBarManagerService: manageDisableList userId=0 what=0x0 pkg=Window{5c546c6 u0 d0 p6611 cert.iaf.in.certindia/cert.iaf.in.certbytes.Dashboard}
09-05 09:31:23.794 6611-6717/cert.iaf.in.certindia D/OkHttp: --> POST http://172.20.10.4:3000/graphql http/1.1
    Content-Type: application/json; charset=utf-8
    Content-Length: 817
    Accept: application/json
    CONTENT_TYPE: application/json
    X-APOLLO-OPERATION-ID: f11eba08c2592c446cbb82aa6661d864281fc50492d38f76bd5a34d4356816ce
    X-APOLLO-CACHE-KEY: baf6df501ed2bf2484141c8b0754e110
    X-APOLLO-CACHE-FETCH-STRATEGY: NETWORK_ONLY
    X-APOLLO-EXPIRE-TIMEOUT: 0
    X-APOLLO-EXPIRE-AFTER-READ: false
    X-APOLLO-PREFETCH: false
    {"query":"query DataQuery($updated_at: String!) {  cyberNews(updated_at: $updated_at) {    __typename    _id    heading    description    image    created_at  }  cyberAlerts(updated_at: $updated_at) {    __typename    _id    title    description    created_at  }  afnetSecurity(updated_at: $updated_at) {    __typename    _id    heading    description    image    created_at  }  internetSecurity(updated_at: $updated_at) {    __typename    _id    heading    description    image    created_at  }  cyberToons(updated_at: $updated_at) {    __typename    _id    title    video    image    created_at  }  cyberCases(updated_at: $updated_at) {    __typename    _id    title    file    created_at  }  certContacts(updated_at: $updated_at) {    __typename    _id    details    created_at  }}","variables":{"updated_at":"0"}}
    --> END POST (817-byte body)
09-05 09:31:23.794 1682-3117/? D/InputDispatcher: Focus entered window: 6611
09-05 09:31:23.794 1682-1944/? D/PointerIcon: setMouseIconStyle1 pointerType: 1001 iconType:101 flag:0 pid:1682 uid:1000
    setMouseCustomIcon IconType is same.101
09-05 09:31:23.814 6611-6611/cert.iaf.in.certindia D/TextView: setTypeface with style : 0
09-05 09:31:23.834 6611-6611/cert.iaf.in.certindia D/TextView: setTypeface with style : 0
09-05 09:31:23.854 6611-6611/cert.iaf.in.certindia D/TextView: setTypeface with style : 0
09-05 09:31:23.864 6611-6611/cert.iaf.in.certindia D/TextView: setTypeface with style : 0
09-05 09:31:23.884 6611-6611/cert.iaf.in.certindia D/TextView: setTypeface with style : 0
09-05 09:31:23.904 6611-6611/cert.iaf.in.certindia D/TextView: setTypeface with style : 0
09-05 09:31:23.914 6611-6611/cert.iaf.in.certindia D/TextView: setTypeface with style : 0
09-05 09:31:23.934 6611-6717/cert.iaf.in.certindia D/OkHttp: <-- 200 OK http://172.20.10.4:3000/graphql (135ms)
    X-Powered-By: Express
    Content-Type: application/json; charset=utf-8
    Content-Length: 9314
    Date: Wed, 05 Sep 2018 04:03:22 GMT
    Connection: keep-alive
    {
      "data": {
        "cyberNews": [
          {
            "__typename": "CyberNewsType",
            "_id": "5b8a6b1d4f06125bb5a6f5d2",
            "heading": "China Probes Suspected Customer Data Leak at Accor Partner",
            "description": "<p><strong>Shanghai police said they were investigating a suspected data leak at NASDAQ-listed Chinese hotelier Huazhu Group, the local partner of France-based AccorHotels.</strong></p><p>Huazhu, one of China&rsquo;s biggest hoteliers, released a statement on Tuesday saying it had alerted police to reports that the company&#39;s internal data was being sold online, asking them to investigate.</p><p>Chinese media reports said the data included guest membership information, personal IDs, check-in records, guest names, mobile numbers, and emails.</p><p>Police in Shanghai said in a statement that they were looking into the case.</p><p>Huazhu&#39;s website said it operates more than 3,000 hotels in more than 370 cities in China, including the AccorHotels brands Ibis and Mercure.</p><p>Shanghai-based Huazhu formed a long-term alliance with Accor in 2014 to help the French hotel group develop the Chinese market.</p><p>Huazhu said the release of the data had caused a &quot;vicious impact&quot;, without giving specifics, and that it was conducting an internal investigation.</p><p>The sale of personal information is common in China, which last year implemented a controversial cybersecurity law that requires services to store user data in China and receive approval from users before sharing their details.</p><p>Chinese e-commerce giant Alibaba came under fire earlier this year over its handling of user data in an episode that underscores growing concerns for privacy in the hyper-digitised country.</p><p>Alibaba&#39;s online-payments affiliate Ant Financial was forced to apologise after users said they felt misled into allowing its Alipay service to share data on their spending habits with Ant&#39;s credit-scoring arm and other third-party services. &nbsp;</p>",
            "image": "uploads/1535798045242e9605ae60342d5e2_index.png",
            "created_at": "1535798045247"
          },
          {
            "__typename": "CyberNewsType",
            "_id": "5b5c2f36de3ff51e915747fe",
            "heading": "Cyber News Heading",
            "description": "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32.",
            "image": "uploads/1532768053982490b1c26e07fa274_Screenshot (4).png",
            "created_at": "1532768054007"
          }
        ],
        "cyberAlerts": [
          {
            "__typename": "CyberAlertsType",
            "_id": "5b8a6b3a4f06125bb5a6f5d3",
            "title": "Cyber Alert Heading",
            "description": "<p><strong>Shanghai police said they were investigating a suspected data leak at NASDAQ-listed Chinese hotelier Huazhu Group, the local partner of France-based AccorHotels.</strong></p><p>Huazhu, one of China&rsquo;s biggest hoteliers, released a statement on Tuesday saying it had alerted police to reports that the company&#39;s internal data was being sold online, asking them to investigate.</p><p>Chinese media reports said the data included guest membership information, personal IDs, check-in records, guest names, mobile numbers, and emails.</p><p>Police in Shanghai said in a statement that they were looking into the case.</p><p>Huazhu&#39;s website said it operates more than 3,000 hotels in more than 370 cities in China, including the AccorHotels brands Ibis and Mercure.</p><p>Shanghai-based Huazhu formed a long-term alliance with Accor in 2014 to help the French hotel group develop the Chinese market.</p><p>Huazhu said the release of the data had caused a &quot;vicious impact&quot;, without giving specifics, and that it was conducting an internal investigation.</p><p>The sale of personal information is common in China, which last year implemented a controversial cybersecurity law that requires services to store user data in China and receive approval from users before sharing their details.</p><p>Chinese e-commerce giant Alibaba came under fire earlier this year over its handling of user data in an episode that underscores growing concerns for privacy in the hyper-digitised country.</p><p>Alibaba&#39;s online-payments affiliate Ant Financial was forced to apologise after users said they felt misled into allowing its Alipay service to share data on their spending habits with Ant&#39;s credit-scoring arm and other third-party services. &nbsp;</p>",
            "created_at": "1535798074788"
          },
          {
            "__typename": "CyberAlertsType",
            "_id": "5b5e0e524612f1737cafeaab",
09-05 09:31:23.934 6611-6611/cert.iaf.in.certindia D/TextView: setTypeface with style : 0
09-05 09:31:23.934 6611-6717/cert.iaf.in.certindia D/OkHttp:         "title": "Be aware of Phishing pages",
            "description": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum",
            "created_at": "1532890706911"
          }
        ],
        "afnetSecurity": [
          {
            "__typename": "AfnetSecurityType",
            "_id": "5b5c425d1cdad99c399c84a6",
            "heading": "Afnet Security Testing",
            "description": "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum et Malorum\" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, \"Lorem ipsum dolor sit amet..\", comes from a line in section 1.10.32.",
            "image": "uploads/15327729576983cdcd3b863b54b4f_Screenshot (3).png",
            "created_at": "1532772957719"
          }
        ],
        "internetSecurity": [
          {
            "__typename": "InternetSecurityType",
            "_id": "5b5c482e1cdad99c399c84a8",
            "heading": "Internet Security Testing",
            "description": "There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.",
            "image": "uploads/1532774446246d203aa8afc24e770_Screenshot (10).png",
            "created_at": "1532774446254"
          }
        ],
        "cyberToons": [
          {
            "__typename": "CyberToonsType",
            "_id": "5b5c5b3b5624757982aae048",
            "title": "Be aware of Phishing pages",
            "video": "uploads/1532779323030a469ad9a7f53d998_Be aware of Phishing pages.mp4",
            "image": "uploads/thumbnail/15327793235337957e79e737b91ec.png",
            "created_at": "1532779323536"
          }
        ],
        "cyberCases": [
          {
            "__typename": "CyberCasesType",
            "_id": "5b5f5d8360ebc53f71cfcfc6",
            "title": "test upload",
            "file": "uploads/153297651592529844c7d8b483929_MP_Plan_1000491466_2018071_.pdf",
            "created_at": "1532976515931"
          },
          {
            "__typename": "CyberCasesType",
            "_id": "5b3902f811f5243e247e0c83",
            "title": "This is Test Cyber Case uploaded for Test Purpose",
            "file": "uploads\\1530462968944dc63c6005a6a13c4_test.pdf",
            "created_at": "1530462968949"
          }
        ],
        "certContacts": [
          {
            "__typename": "CertContactsType",
            "_id": "5b5e0f0ef5a98e8174db2c3e",
            "details": "445 Mount Eden Road, \nMount Eden, \nAuckland.",
            "created_at": "1532890894547"
          }
        ]
      }
    }
    <-- END HTTP (9314-byte body)
09-05 09:31:23.984 6611-6717/cert.iaf.in.certindia D/CERTBYTES_LOG: On Exception
    com.apollographql.apollo.exception.ApolloParseException: Failed to parse http response
09-05 09:31:23.984 6611-6611/cert.iaf.in.certindia D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 48 - 0, 0) vi=Rect(0, 48 - 0, 0) or=1
09-05 09:31:23.984 1682-3113/? D/InputMethodManagerService: windowGainedFocus mCurrentFocusedUserId - 0 and mSecureKeypadEnabled-false
09-05 09:31:23.994 1682-1944/? D/KnoxTimeoutHandler: notifyActivityDrawn [MsgParam] userId: 0 fullscreen is true showWhenlocked is false
09-05 09:31:23.994 1682-1682/? D/KnoxTimeoutHandler: activityDrawn [MsgParam] userId: 0 fullscreen is true showWhenlocked is false
09-05 09:31:23.994 1682-1944/? I/ActivityManager: Displayed cert.iaf.in.certindia/cert.iaf.in.certbytes.Dashboard: +642ms

全栈跟踪

09-07 21:23:09.032 20812-21143/cert.iaf.in.certindia W/System.err: com.apollographql.apollo.exception.ApolloParseException: Failed to parse http response
        at com.apollographql.apollo.internal.interceptor.ApolloParseInterceptor.parse(ApolloParseInterceptor.java:101)
        at com.apollographql.apollo.internal.interceptor.ApolloParseInterceptor.access$100(ApolloParseInterceptor.java:28)
        at com.apollographql.apollo.internal.interceptor.ApolloParseInterceptor$1.onResponse(ApolloParseInterceptor.java:53)
        at com.apollographql.apollo.internal.interceptor.ApolloServerInterceptor$1$1.onResponse(ApolloServerInterceptor.java:93)
        at okhttp3.RealCall$AsyncCall.execute(RealCall.java:153)
        at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at java.lang.Thread.run(Thread.java:818)
    Caused by: java.lang.IllegalArgumentException: Can't map GraphQL type: ObjectId to: class java.lang.Object. Did you forget to add custom type adapter?
        at com.apollographql.apollo.internal.response.ScalarTypeAdapters.adapterFor(ScalarTypeAdapters.java:30)
        at com.apollographql.apollo.internal.response.RealResponseReader.readCustomType(RealResponseReader.java:187)
        at cert.iaf.in.certbytes.CertbytesQuery$Cybernews$Mapper.map(CertbytesQuery.java:339)
        at cert.iaf.in.certbytes.CertbytesQuery$Data$Mapper$1$1.read(CertbytesQuery.java:221)
        at cert.iaf.in.certbytes.CertbytesQuery$Data$Mapper$1$1.read(CertbytesQuery.java:218)
        at com.apollographql.apollo.internal.response.RealResponseReader$ListItemReader.readObject(RealResponseReader.java:306)
        at cert.iaf.in.certbytes.CertbytesQuery$Data$Mapper$1.read(CertbytesQuery.java:218)
        at cert.iaf.in.certbytes.CertbytesQuery$Data$Mapper$1.read(CertbytesQuery.java:215)
        at com.apollographql.apollo.internal.response.RealResponseReader.readList(RealResponseReader.java:163)
        at cert.iaf.in.certbytes.CertbytesQuery$Data$Mapper.map(CertbytesQuery.java:215)
        at cert.iaf.in.certbytes.CertbytesQuery$Data$Mapper.map(CertbytesQuery.java:210)
        at com.apollographql.apollo.internal.response.OperationResponseParser$1.read(OperationResponseParser.java:56)
        at com.apollographql.apollo.internal.json.ResponseJsonStreamReader.nextObject(ResponseJsonStreamReader.java:86)
        at com.apollographql.apollo.internal.response.OperationResponseParser.parse(OperationResponseParser.java:51)
        at com.apollographql.apollo.internal.interceptor.ApolloParseInterceptor.parse(ApolloParseInterceptor.java:87)
java android graphql apollo apollo-client
1个回答
0
投票

引起:java.lang.IllegalArgumentException:无法将GraphQL类型:ObjectId映射到:class java.lang.Object。您是否忘记添加自定义类型适配器?

我有同样的错误,只是我的GraphQL type不同。解决这个问题的方法是在你的ApolloClient中添加一个CustomTypeAdapter,例如:

  1. app/build.gradle中定义映射
apollo {
  customTypeMapping = [
     //or java.lang.Long
     "ObjectId" : "java.lang.Integer" 
  ]
}
  1. 创建CustomTypeAdapter并将其添加到ApolloClient
objectIDCustomTypeAdapter = new CustomTypeAdapter<Integer>() {
      @Override public Integer decode(CustomTypeValue value) {
        try {
          return Integer.parseInt(value.toString());
        } catch (Exception e) { //NumberFormatException
          e.printStackTrace()
        }
      }

      @Override public CustomTypeValue encode(Integer value) {
        //assumption; I am not sure about the `Number` part
        return new CustomTypeValue.GraphQLNumber(value);
      }
    };

ApolloClient.builder()
  .serverUrl(serverUrl)
  .okHttpClient(okHttpClient)
  //ObjectId changes to all caps
  .addCustomTypeAdapter(CustomType.OBJECTID, objectIDCustomTypeAdapter) 
  .build();

来源(及更多信息):apollo graphql android docs

© www.soinside.com 2019 - 2024. All rights reserved.