How to remove exception from headers in Okhttp - retrofit2

I am making an authorized call from the using token. Firstly the user gets a token after sign in, I stores that token in shared preferences, and passed that token(stored as string) as header to retrofit api call using okhttp as client. Now getting this error. How to encode the header/ token or remove this error.
[example of token I get from API : "Du_jwJP64Znbwc1EvyJMEkw9HHwIZPjYnXgchiq5e2Tf24y9vNBrD6PJX8jTMj7qGDQyxTDBW8XrlwSRBjNQ-Tzzafq7r3jS5x9ZsXJgU9JgDi8ZNmwf_JD47aTRUKEhX5KtZ52oOeiuOnjO9XKCKT2g1vLpmcpUxvOi36R6ySNoMBmWzn7KmG6_vZzhfT0YhhfIW8x6vPEHmDLvBIIWbBDry0qpoiZNkgkI2D6CkFqQN1Hy-fMc3tFX7Y-VPRBF6bXQOHbsDAPkSqFfVxMQaw "]
API service interface :
#FormUrlEncoded #Multipart #POST("api/user/info") #Headers({"Content-Type:application/json"}) Call
<QRcodeResponse> getUserinfo(#Header("Authorization") String Auth);
java.lang.IllegalArgumentException: Unexpected char 0x20 at 12 in header name: Content-Type
at okhttp3.Headers$Builder.checkNameAndValue(Headers.java:330)
at okhttp3.Headers$Builder.add(Headers.java:288)
at retrofit2.ServiceMethod$Builder.parseHeaders(ServiceMethod.java:329)
at retrofit2.ServiceMethod$Builder.parseMethodAnnotation(ServiceMethod.java:270)
at retrofit2.ServiceMethod$Builder.build(ServiceMethod.java:175)
at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:170)
at retrofit2.Retrofit$1.invoke(Retrofit.java:147)
at java.lang.reflect.Proxy.invoke(Proxy.java:1006)
at $Proxy0.getUserinfo(Unknown Source)
at com.example.two_locally.sign_in.updateContent(sign_in.java:209)
at com.example.two_locally.sign_in.access$000(sign_in.java:45)
at com.example.two_locally.sign_in$3.onResponse(sign_in.java:160)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:227)
at android.app.ActivityThread.main(ActivityThread.java:7822)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1026)

You have an extra space in your #Header annotation on your service interface.

Related

Servicestack JsonClient - Object reference not set to an instance of an object

We have a basic servicestack frontend that sends using the jsonclient to backend services and works for the past few years.
I am trying to investigate why we are receiving the below exception on any frontend JSON Client.get requests,
System.NullReferenceException
Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Collections.Specialized.NameObjectCollectionBase.BaseGetAllKeys()
at System.Collections.Specialized.NameValueCollection.get_AllKeys()
at ServiceStack.PclExportClient.AddHeader(WebRequest webReq, NameValueCollection headers)
at ServiceStack.ServiceClientBase.PrepareWebRequest(String httpMethod, String requestUri, Object request, Action`1 sendRequestAction)
at ServiceStack.ServiceClientBase.SendRequest(String httpMethod, String requestUri, Object request)
at ServiceStack.ServiceClientBase.Send[TResponse](String httpMethod, String relativeOrAbsoluteUrl, Object request)
at ABC.api.InitializationService.Any(InitializationRequest request) in C:\.....\api\InitializationService.cs:line 27
It's strange, and i'm trying to reproduce this issue by hitting the breakpoint, and nulling / modifying the headers, but can't reproduce or figure out what this issue is.
To me, doesn't the exception imply the header base keys are null, and it can't be retrieved - but how does that occur ?
Using ServiceStack 5.80
ASP.NET MVC
.Net Framework 4.6.1
EDIT:
Calling line of code that produces this issue is
var deviceResult = client.Get(new DRequest{ U = r.D });

Spring Integration WebFlux inboundGateway replyChannel for error response

Trying to use the replyChannel for sending an error response for the WebFlux.inboundGateway, however no response is sent from ErrorFlow and the client continues to wait for response. Kindly suggest.
return IntegrationFlows.from(WebFlux.inboundGateway("/some/uri")
.requestMapping(m -> m.methods(POST))
.requestPayloadType(SomeObject.class)
.replyChannel(webReplyChannel)
.errorChannel(appErrorChannel))
#Bean
public IntegrationFlow appErrorFlow() {
return IntegrationFlows.from(appErrorChannel())
.<ErrorMessage, Message<String>> transform(errorMessage -> MessageBuilder.withPayload("Error Response")
.copyHeaders(((MessagingException) errorMessage.getPayload()).getFailedMessage().getHeaders())
.build())
.get();
Exception:
2023-01-14 13:34:10,343 [reactor-http-nio-2 ] ERROR o.s.i.h.LambdaMessageProcessor - 1283c6fd42485bf5 Could not invoke the method 'public java.lang.Object com.xxxxxxxxxxx.xxxxx..ErrorFlowConfig$$Lambda$2129/0x0000000801ac3a00.transform(java.lang.Object)' due to a class cast exception, if using a lambda in the DSL, consider using an overloaded EIP method that takes a Class<?> argument to explicitly specify the type. An example of when this often occurs is if the lambda is configured to receive a Message<?> argument.
java.lang.ClassCastException: class com.xxxxxxx.model.dto.SomeObject cannot be cast to class org.springframework.messaging.support.ErrorMessage (com.xxxxxxx.model.dto.SomeObject is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader #32f93dff; org.springframework.messaging.support.ErrorMessage is in unnamed module of loader 'app')
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at org.springframework.integration.handler.LambdaMessageProcessor.processMessage(LambdaMessageProcessor.java:105)
at org.springframework.integration.transformer.AbstractMessageProcessingTransformer.transform(AbstractMessageProcessingTransformer.java:115)
at o
This is known framework limitation: https://github.com/spring-projects/spring-integration/issues/3984.
So, for now you have to do like this instead:
.transform(Message.class,
errorMessage ->
MessageBuilder.withPayload("Error Response")
.copyHeaders(((MessagingException) errorMessage.getPayload()).getFailedMessage().getHeaders())
.build())
Only those getFailedMessage().getHeaders() contain respective replyChannel and errorChannel headers.

Migration to EWS API for sending emails

I have the following code to send a email through EWS API,
ExchangeService service = new ExchangeService();
service.setUrl(new URI(**MyExchangeURL**));
ExchangeCredentials credentials = new WebCredentials(**UserName**, **Password**);
service.setCredentials(credentials);
EmailMessage message = new EmailMessage(service);
message.setSubject("EWS Test Mail");
message.setBody(MessageBody.getMessageBodyFromText("This is a test mail from EWS"));
message.getToRecipients().add("Test#gmail.com");
message.send();
With the above code, I facing a null pointer exception when message.send() is called.
Log:
Exception in thread "main" microsoft.exchange.webservices.data.core.exception.service.remote.ServiceRequestException: The request failed. null
at microsoft.exchange.webservices.data.core.request.SimpleServiceRequestBase.internalExecute(SimpleServiceRequestBase.java:74)
at microsoft.exchange.webservices.data.core.request.MultiResponseServiceRequest.execute(MultiResponseServiceRequest.java:158)
at microsoft.exchange.webservices.data.core.ExchangeService.internalCreateItems(ExchangeService.java:598)
at microsoft.exchange.webservices.data.core.ExchangeService.createItem(ExchangeService.java:657)
at microsoft.exchange.webservices.data.core.service.item.Item.internalCreate(Item.java:245)
at microsoft.exchange.webservices.data.core.service.item.EmailMessage.internalSend(EmailMessage.java:147)
at microsoft.exchange.webservices.data.core.service.item.EmailMessage.send(EmailMessage.java:258)
at EWS.main(EWS.java:28)
Caused by: java.lang.NullPointerException
at microsoft.exchange.webservices.data.core.request.ServiceRequestBase.readResponse(ServiceRequestBase.java:369)
at microsoft.exchange.webservices.data.core.request.SimpleServiceRequestBase.internalExecute(SimpleServiceRequestBase.java:63)
... 7 more
When debugged further there is a mismatch in the attribute name.
In request, the attribute is contentType is setted in request. But while reading the response, we are getting Null as code used have Content-type. There is a mismatch in the attribute name being set and read.
Is anyone else facing this issue or any workaround?

Howto register a webhook with AuthType=HttpHeader using "Dynamics 365 Web API"

To register a webhook on Dynamics 365 there is a tool called Plug-in Registration (https://learn.microsoft.com/en-us/powerapps/developer/data-platform/register-web-hook).
However, I would like to automate the webhook registration process and thus would like to use the Web API endpoint for webhook registration:
/api/data/v9.2/serviceendpoints
The problem I have is the setting of the value for the parameter authvalue in the JSON request body, because I want to use Http Header authtype:
{
"name": "Test Webhook",
"url": "https://myendpoint",
"contract": 8,
"authtype": 5,
"authvalue": "<========= ??? what comes here ???"
}
Assuming I want to have this header be sent to my webhook endpoint:
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
What would be the value of authvalue in the JSON above ?
The value should be a string according to the data type of authvalue, but how that should be formatted?
If I use the value Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ= as is for authvalue,
when the webhook is fired, I got the following error in System Job:
Plugin Trace:
[Microsoft.Crm.ServiceBus: Microsoft.Crm.ServiceBus.WebhookPlugin]
[ad9a4124-ab57-ec11-8f8f-6045bd8aed3b: Test for Step Creation]
Error Message:
System.ServiceModel.FaultException`1[Microsoft.Xrm.Sdk.OrganizationServiceFault]:
The webhook call failed because of invalid http headers in authValue.
Check if the authValue format, header names and values are valid for
your Service Endpoint entity. (Fault Detail is equal to Exception
details: ErrorCode: 0x80050203 Message: The webhook call failed
because of invalid http headers in authValue. Check if the authValue
format, header names and values are valid for your Service Endpoint
entity. TimeStamp: 2021-12-08T10:15:26.8637496Z
-- Exception details: ErrorCode: 0x80040216 Message: Received exception when adding custom http headers: for
OrgId:xxxxxx-925f-4958-9aee-xxxxxxxxxxxx, serviceEndpointId:
c099d16c-a057-ec11-8f8f-6045bd8aed3b, name: Test Webhook,
exception:System.Xml.XmlException: Data at the root level is invalid.
Line 1, position 1. at System.Xml.XmlTextReaderImpl.Throw(Exception
e) at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace() at
System.Xml.XmlTextReaderImpl.ParseDocumentContent() at
System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean
preserveWhitespace) at System.Xml.XmlDocument.Load(XmlReader
reader) at System.Xml.XmlDocument.LoadXml(String xml) at
Microsoft.Crm.ServiceBus.WebhookClient.ExtractKe...).
For HtppHeader authentication type the key value pair for AuthValue must be set in the following xml format:
<settings><setting name="Authorization" value="Basic dXNlcm5hbWU6cGFzc3dvcmQ=" /></settings>

Google Sites API caused com.google.appengine.api.urlfetch.URLFetchServiceImpl.fetch(URLFetchServiceImpl.java:52)

java.lang.RuntimeException: Unable to complete the HTTP request
at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.getHeaderFields(URLFetchServiceStreamHandler.java:217)
at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.getHeaderFields(URLFetchServiceStreamHandler.java:73)
at com.google.gdata.client.http.HttpGDataRequest.isOAuthProxyErrorResponse(HttpGDataRequest.java:566)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:557)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:538)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:536)
at com.google.gdata.client.Service.getFeed(Service.java:1135)
at com.google.gdata.client.Service.getFeed(Service.java:998)
at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:645)
at com.google.gdata.client.Service.getFeed(Service.java:1017)
at com.jabil.sites.subscription.service.GoogleSitesService.getFirstContentFeed(GoogleSitesService.java:72)
at com.jabil.sites.subscription.service.GoogleSitesService.sendNotification(GoogleSitesService.java:150)
at com.jabil.sites.subscription.servlet.NotifyUsersServlet.sendNotification(NotifyUsersServlet.java:60)
at com.jabil.sites.subscription.servlet.NotifyUsersServlet.doGet(NotifyUsersServlet.java:40)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:123)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:125)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.DevAppServerServersFilter.doDirectRequest(DevAppServerServersFilter.java:369)
at com.google.appengine.tools.development.DevAppServerServersFilter.doDirectServerRequest(DevAppServerServersFilter.java:352)
at com.google.appengine.tools.development.DevAppServerServersFilter.doFilter(DevAppServerServersFilter.java:115)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:94)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:421)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:547)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Caused by: java.net.SocketTimeoutException: Timeout while fetching: https://sites.google.com/feeds/content/mydomain.com/global-communications-programs
at com.google.appengine.api.urlfetch.URLFetchServiceImpl.fetch(URLFetchServiceImpl.java:52)
at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.fetchResponse(URLFetchServiceStreamHandler.java:417)
at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.getInputStream(URLFetchServiceStreamHandler.java:296)
at com.google.apphosting.utils.security.urlfetch.URLFetchServiceStreamHandler$Connection.getHeaderFields(URLFetchServiceStreamHandler.java:212)
... 50 more
Jun 20, 2013 9:46:40 PM com.mydomain.sites.subscription.service.GoogleSitesService sendNotification
I have this exception message thrown when accessing into this Google Site via Google Sites API. There is no problem when accessing other Google Sites with via Google Sites API.
This is the programming:
private static ContentFeed getFirstContentFeed(SitesService service, String siteName, Credential credential) throws Exception {
// Configure URL as Google Sites content feed
String url = String.format(
"%s/%s/%s",
GoogleOAuth2Constant.GOOG_SITES_CONTENT_FEED,
ReadXmlConfigurationService.getNode("domain"),
siteName);
// Assign Google credential into SitesService
service.setOAuth2Credentials(credential);
// Use HTTP-SSL to call Google Sites API
service.useSsl();
// Retrieve site contents
return service.getFeed(new URL(url), ContentFeed.class);
}
This line caused the exception thrown:
return service.getFeed(new URL(url), ContentFeed.class);
Well, I don't think my programming portion caused the issue because it somehow managed to be called after retries.
Had it solved by adding setConnectionTimeout()
private static ContentFeed getFirstContentFeed(SitesService service,
String siteName,
Credential credential) throws Exception {
// Configure URL as Google Sites content feed
String url = String.format(
"%s/%s/%s/",
GoogleOAuth2Constant.GOOG_SITES_CONTENT_FEED,
ReadXmlConfigurationService.getNode("domain"),
siteName);
// Assign Google credential into SitesService
service.setOAuth2Credentials(credential);
// Use HTTP-SSL to call Google Sites API
service.useSsl();
// Set HTTP timeout for 2 minutes for larger feed
service.setConnectTimeout(120000);
// Retrieve site contents
return service.getFeed(new URL(url), ContentFeed.class);
}

Resources