How can we get response body from DataRequest object? I am using RxAlomafire.request method for making http calls. Need some data from response body when http request fails.
Related
I try to call an API with Go. When using Postman everything is OK. But if I use the Go code from Postman the response is garbled/unclear.
Down below the code I'm using:
func CallAPI() {
url := "https://url"
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("Authorization", "Bearer Token is normaly here")
req.Header.Add("User-Agent", "PostmanRuntime/7.19.0")
req.Header.Add("Accept", "Accept: application/json")
req.Header.Add("Cache-Control", "no-cache")
req.Header.Add("Postman-Token", "Postman token normaly here")
req.Header.Add("Host", "host normaly here")
req.Header.Add("Accept-Encoding", "gzip, deflate")
req.Header.Add("Connection", "keep-alive")
req.Header.Add("cache-control", "no-cache")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(string(body))
}
The response I get when I use fmt.Println(string(body)) looks like below. I also tried other API's with this code and had the same result.
r�痱�
I also tried to unmarshal the json to a struct and did get the following error
Invalid character '\x1f' looking for beginning of value
I think it's something about decoding. But I don't know what.
You ask the server to send the content compressed (req.Header.Add("Accept-Encoding", "gzip, deflate")), and that's what you get: a gzip response, indicated by the response header: Content-Encoding:[gzip].
Remove that header (don't set Accept-Encoding request header), and you should get plain JSON response. Or decode the gzip response yourself.
Note that if you omit this header, the default transport will still request gzip encoding, but then it will also transparently decode it. Since you request it explicitly, transparent, automatic decoding does not happen. This is documented at Transport.DisableCompression field:
// DisableCompression, if true, prevents the Transport from
// requesting compression with an "Accept-Encoding: gzip"
// request header when the Request contains no existing
// Accept-Encoding value. If the Transport requests gzip on
// its own and gets a gzipped response, it's transparently
// decoded in the Response.Body. However, if the user
// explicitly requested gzip it is not automatically
// uncompressed.
DisableCompression bool
I am using HttpWebRequest for fetching data from Rest API.
I have proxy applied on my system and I need to authorize with Proxy Server in order to fetch data from Rest API.
For Authorization, I am using Proxy-Authorization header with value as "Basic base64_credentials".
But even after sending these credentials, I am not able to authorize with Proxy Server.
If I hit same Rest API from Postman by giving Proxy-Authorization header it works perfectly.
Here is my code :
Dim myHttpWebRequest As HttpWebRequest = DirectCast(HttpWebRequest.Create(uri), HttpWebRequest)
myHttpWebRequest.Headers.Add("Proxy-Authorization", "Basic dXNlcjE6UGFzc3dvcmQx")
myHttpWebRequest.Method = "GET"
myHttpWebRequest.AutomaticDecompression = DecompressionMethods.Deflate Or DecompressionMethods.GZip Or DecompressionMethods.None
Dim myHttpWebResponse = GetresponseForRequest(myHttpWebRequest)
What could be the possible reason for this?
I have not touched HttpWebRequest.Proxy settings.
I'm trying to create a REST API from a SOAP Service using IBM API Connect 5. I have followed all the steps described in this guide (https://www.ibm.com/support/knowledgecenter/en/SSFS6T/com.ibm.apic.apionprem.doc/tutorial_apionprem_expose_SOAP.html).
So, after dragging the web service block from palette, ensuring the correctness of endpoint and publishing the API, I have tried to call the API from the browser. Unfortunately, the API return the following message:
<errorResponse>
<httpCode>500</httpCode>
<httpMessage>Internal Server Error</httpMessage>
<moreInformation>Error attempting to read the urlopen response
data</moreInformation>
</errorResponse>
To testing purpose, I have logged the request and I have tried the request on SOAPUI. The service return the response correctly.
What is the problem?
In my case, the problem was in the backend charset (Content-Type: text/xml;charset=iso-8859-1).
For example, backend returns text/xml in German (or French). Api Connect cannot process character ü. It needs Content-Type: text/xml;charset=UTF-8.
I had a similar issue, in my case was the accept. if you have an Invoke and the content-type or the accept, is not matching the one of the request, or the response that you got, APIC is getting mad.
Please, check if the formats to send (contentType) and receive (accept) are the same of that your API expected. In my case the error occurs because the API returns a String and my default code is configured to receive a JSON body.
//define a JSON-PLAIN TEXT protocol
private HttpEntity<String> httpEntityWithBody(Object objToParse){
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + "xxx token xxx");
headers.set("Accept", MediaType.TEXT_PLAIN_VALUE);
headers.setContentType(MediaType.APPLICATION_JSON);
Gson gson = new GsonBuilder().create();
String json = gson.toJson(objToParse);
HttpEntity<String> httpEntity = new HttpEntity<String>(json, headers);
return httpEntity;
}
//calling the API to APIC...
ParameterizedTypeReference<String> responseType = new
ParameterizedTypeReference<String>(){};
ResponseEntity<String> result =
rest.exchange(builder.buildAndExpand(urlParams).toUri(), HttpMethod.PUT, httpEntityWithBody(myDTO), responseType);
String statusCode = result.getStatusCodeValue();
String message = result.getBody();
How can I retrieve the body I sent from a xhr (XMLHttpRequest) send(body) call?.
My xhr variable is an XMLHttpRequest ready to call an internal url using the POST method (Ex: /path/api )
xhr.send("a=1");
On the other side, I have implemented a Service Worker and created the handler to catch all fetch requests
self.addEventListener('fetch', function(event, body)
{
event.respondWith( //Check content of event.request.body to run the right action );
}
I can retrieve some properties of the event.request as event.request.url, but I am unable to find the way to retrieve my original xhr body (i.e. "a=1").
Interestingly, when the Service Worker handles this request, and calls the network to get the result,
return fetch(event.request);
the server get access to the body data.
Below an extract of the Request object I receive within the SW fetch method
Request {method: "POST", url: "http://localhost/services", headers: Headers
, referrer: "http://localhost/m1/", referrerPolicy: "no-referrer-when-downgrade"…}
bodyUsed:false
credentials:"include"
headers:Headers
__proto__:Headers
integrity:""
method:"POST"
mode:"cors"
redirect:"follow"
referrer:"http://localhost/path/"
referrerPolicy:"no-referrer-when-downgrade"
url:"http://localhost/path/api"
Any suggestion on how to retrieve the content/body of the send request within the Service Worker fetch() capture?
Thanks!
This is maybe obvious for most people, but I wanted to add some notes with the response, in case someone is in my same situation in the future.
There are several methods to retrieve the body from the request, depending on how the body has been sent
event.request.arrayBuffer()
event.request.blob()
event.request.json()
event.request.text()
event.request.formData()
Any of those methods will return a Promise, which will include the body content. Voila!
I need to thank also Nikhil Marathe (https://hacks.mozilla.org/2015/03/this-api-is-so-fetching/) for helping me understand how all this works.
I am new in elm and try to consume web api using http post request with header and body using 0.17.1 version but did not get any documentation.
So any one help me to implement this functionality
The send method of the Http package gives you the possibility to create and send a custom request. For example, a post request could be something like
postRequest : Request
postRequest =
{ verb = "POST"
, headers =
[ ("Origin", "http://elm-lang.org")
, ("Access-Control-Request-Method", "POST")
, ("Access-Control-Request-Headers", "X-Custom-Header")
]
, url = "http://example.com/hats"
, body = empty
}
You can then create the Task that represent the request using the send function like
send defaultSettings postRequest