500 error on api request. works fine when called through browser - api

Hello I have an api which authenticates the user login . Now when I hit this rest service in my browser it displays the result but when I try to do this using my code it gives in 500 error. Please help me with this .
My Api: http://abhinavevent2014.sched.org/api/auth/login?api_key=1309658400d57c8cfc6081f8361de52c&username=abhinavm#test.com&password=test
string url = #"http://abhinavevent2014.sched.org/api/auth/login?api_key=1309658400d57c8cfc6081f8361de52c&username=abhinavm#test.com&password=test";
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
WebRequest requestfriend = WebRequest.Create(url);
WebResponse responsefriend = requestfriend.GetResponse(); ( This is where it blows)
Stream streamResponse = responsefriend.GetResponseStream();
StreamReader streamReaderResponse = new StreamReader(streamResponse, encode);
jsonResult = streamReaderResponse.ReadToEnd();
return jsonResult.ToString();

You need to use User-Agent in the headers, as the documentation says:
You must also send requests with a User-Agent in the headers, as Sched
filters out requests with no User-Agent.
Sched API Doc
Browser automatically does that, so it can retrieve the data.

Related

Updating stock on magento 2.1 using REST API - Error {"message": "Request does not match any route."}

I am trying to get a stock item quantity updated on a magento 2.1 site using REST API.
I am coding in VB.net but I get the error JSON response {"message": "Request does not match any route."}
Dim Access_Token = "XXXXXXXXXXXXX"
Try
Dim VATWebClient = New WebClient()
VATWebClient.Headers(HttpRequestHeader.Accept) = "application/json"
VATWebClient.Headers(HttpRequestHeader.ContentType) = "application/json"
VATWebClient.Headers(HttpRequestHeader.Authorization) = "Authorization Bearer " & Access_Token
Dim Response As String
Response = VATWebClient.UploadString("http://www.xxxxxx.com/rest/V1/products/xxxx/stockItems/1", "{""stockItem"":{""qty"":100}}")
Catch webEx As WebException
Dim errorMessage As String = webEx.Message
Dim errorStack As String = webEx.StackTrace
End Try
I have also tried to setup SoapUI just to test to make sure that I am calling it right and I get the same error.
I read somewhere that the webapi.xml must be updated with the API which is required I am really hoping that's not the case as the host/web developer is not very accessible!
UploadString will create a POST Request, as you can see form the API Docs, this API endpooint is PUT method only.
https://devdocs.magento.com/swagger/index_21.html#!/catalogInventoryStockRegistryV1/catalogInventoryStockRegistryV1UpdateStockItemBySkuPut
I'm not too sure how to change the method in visual basic, but I'm sure it's not too difficult.

HTTPWebrequest successfully fetched result even when wrong proxy credentials are given

I am trying to hit a rest API using HttpWebRequest and I have to authenticate Proxy Server before I can hit a Rest API.
For authorizing proxy Server, I am adding credentials to HttpWebrequest.Proxy.credentials.
Now, my scenario is that, I am accessing the Rest API twice, first with Correct Proxy Credentials and then with wrong Proxy credentials.
With Correct Proxy Credentials I getthe out put as expected but with wrong credentials I am again able to fetch data from rest API.
If I reverse the order of APIs that is with wrong credentials first and then ith right creentials then I get 407 erro on 1st API hit which is correct.
How is this possible.
Here is my Code :
1st Call :
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)
2nd Call
Dim myHttpWebRequest1 As HttpWebRequest = DirectCast(HttpWebRequest.Create(uri), HttpWebRequest)
myHttpWebRequest1.Headers.Add("Proxy-Authorization", "Basic dXNlcjE8UKFzc3dvcmQn")
myHttpWebRequest1.Method = "GET"
myHttpWebRequest1.AutomaticDecompression = DecompressionMethods.Deflate Or DecompressionMethods.GZip Or DecompressionMethods.None
Dim myHttpWebResponse1 = GetresponseForRequest(myHttpWebRequest)

Proxy-Authorization Header not working in HttpWebRequest, in case of Rest Request to a URL

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.

API Connect 5 - Error attempting to read the urlopen response data

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();

HttpWebRequest not sending cookies on POST

I’m writing a http module to work as a reverse proxy, i.e. receives a request from a browser, sends it on to the target site, receives a response and sends that back to the browser.
Its all working fine, except for a problem with forwarding cookies from the browser request to the target site on a Post. All headers and form data are correct on the outgoing request, but no cookies are included.
I’ve run fiddler on both the request from the browser to IIS and the outgoing httpwebrequest and proven this to be the case. Running the module in debug shows that the cookies are found in the request from the browser and successfully placed in the cookiecontainer of the httpwebrequest, but they just don’t appear in the actual request sent out.
If I hack (in debug) the outgoing request method to a Get, then they go, but they don’t go for a Post.
I’ve also tracked the request/response from a browser direct to the target site using Fiddler, and the request seems identical in all three cases (browser to target, browser to my IIS module, IIS module to target), except that the IIS module to target omits the cookies.
Here’s the code (VB.Net, and tried in 2.0 and 4.5):
' set up the request to the target
Dim reqTarget As System.Net.HttpWebRequest
reqTarget = CType(System.Net.HttpWebRequest.Create(strTargetURL & strTargetPath & qstring), System.Net.HttpWebRequest)
' copy relevant info, cookies etc from the application request to the target request
CopyAppRequest(application.Context.Request, reqTarget)
' send the request and get the response
Dim rspTarget As System.Net.HttpWebResponse = CType(reqTarget.GetResponse(), System.Net.HttpWebResponse)
Private Sub CopyAppRequest(ByRef reqApp As System.Web.HttpRequest, ByRef reqTarget As System.Net.HttpWebRequest)
' copy over the headers
For Each key As String In reqApp.Headers.AllKeys
Select Case key
Case "Host", "Connection", "Content-Length", "Accept-Encoding", "Expect", "Authorization", "If-Modified-Since"
' not sure if we need to process these
Case "Connection"
reqTarget.Connection = reqApp.Headers(key)
Case "Content-Type"
reqTarget.ContentType = reqApp.Headers(key)
Case "Accept"
reqTarget.Accept = reqApp.Headers(key)
Case "Referer"
reqTarget.Referer = reqApp.Headers(key)
Case "User-Agent"
reqTarget.UserAgent = reqApp.Headers(key)
Case "Cookie"
' do nothing, cookies are handled below..
Case Else
reqTarget.Headers.Add(key, reqApp.Headers(key)
End Select
Next
reqTarget.Method = reqApp.HttpMethod
reqTarget.AllowAutoRedirect = False
If reqTarget.Method = "POST" Then
reqTarget.ContentLength = reqApp.ContentLength
Dim datastream() As Byte = System.Text.Encoding.UTF8.GetBytes(reqApp.Form.ToString)
reqTarget.ContentLength = datastream.Length
Dim requestwriter As System.IO.Stream = reqTarget.GetRequestStream
requestwriter.Write(datastream, 0, datastream.Length)
requestwriter.Close()
requestwriter.Dispose()
End If
Dim CookieJar As New System.Net.CookieContainer
reqTarget.CookieContainer = CookieJar
For Each key As String In reqApp.Cookies.AllKeys
Dim tgtCookie As New System.Net.Cookie
With tgtCookie
.Name = reqApp.Cookies.Item(key).Name
.Value = reqApp.Cookies.Item(key).Value
.Domain = ".domain.com"
.Path = "/"
.Expires = DateAdd(DateInterval.Month, 1, System.DateTime.Now)
.HttpOnly = True
End With
CookieJar.Add(tgtCookie)
Next
End Sub
Note: the domain I’m trying to reach is in the form abc.domain.com (i.e. it’s a subdomain, and no www), the reason I’ve tried the .domain.com form is that is the form used in the cookies that are received in the response. I’ve also tried other combinations such as abc.domain.com, .abc.domain.com, etc. Also I’ve tried creating a Uri object and using that method to add the cookie into the cookiecontainer.
I’ve tried everything I can think of and can find on forums…. Anyone got any suggestions? I suspect I’ve missed something obvious!
Of course, any other comments on how the code above can be improved will be appreciated.
Thanks.
Ok, I found the issue...
I was using Fiddler to see what was going on with http, and Fiddler was correct. However, when I used Wireshark, I found that the http request was being sent earlier than I thought, and only on the Post.
It turned out that the requestwriter.write line caused the http request to be sent, not the GetResponse (as is the case with Get). So, anything I changed in the httpwebrequest after the requestwriter.write didn't get sent.
The fix - I just moved all the header and cookie set up above the requestwriter.write and it all worked.
How frustrating, but at least its fixed now :)
If anyone has any feedback on whether I've got something wrong that's causing this to happen, please let me know.