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

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.

Related

Unexpected error occurred on a receive using API on my Wix site

I've made an experimental email and password system using post requests to my Wix site API and I've verified it works through curl and postman. When trying to use it in my VB.NET app however I get the error: "The underlying connection was closed: An unexpected error occurred on a receive." I already previously ran into a "Could not create SSL/TLS secure channel" error but that was resolved when I moved the .NET framework for the project to 4.7.1 and made sure SecurityProtocol was set to SystemDefault as Wix seems to use TLS 1.3. Now however I'm getting this error on receive that I have no idea how to resolve as everything in the request seems to look ok:
ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault
Dim req As HttpWebRequest = DirectCast(WebRequest.Create(New Uri("https://xxxxx.com/mysite/_functions/check?email=" & email & "&pass=" & LCase(passHash))), HttpWebRequest)
req.Method = "POST"
req.ContentType = "none"
req.ContentLength = 0
req.Host = "test"
req.KeepAlive = True
Dim result As HttpWebResponse = req.GetResponse()
The error is thrown when running 'req.GetReponse()'.
After looking at countless versions of sample code for .NET POST requests and questions about this error but everyone seems to suggest setting the security prococol type, which I have done and setting it as the system default is the only way I don't get an internal server error status. Another was setting KeepAlive to false, which I have also tried but didn't make any difference.
What could be the problem here? Here is what's included in the postman header if this is of help:
Ok so eventually I ended up changing my code to use GetResponseAsync() instead of GetResponse() (not that it made any difference to the problem) and set the protocol type back to Tls12 on .NET 4.8. In the end it seemed that having req.Host set was what was causing the issue with the response, Wix doesn't seem to like it. I also added some extra settings to the request but ultimately they make no difference to the response. Here is the final working code:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
Dim req As HttpWebRequest = WebRequest.CreateHttp("https://example.com/check?email=" & email & "&pass=" & LCase(passHash))
req.Method = "POST"
req.ContentType = "none"
req.ContentLength = 0
req.KeepAlive = True
req.CookieContainer = New CookieContainer()
req.UserAgent = "Test"
req.Accept = "ext/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
req.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US;q=0.9,en;q=0.5")
req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate;q=0.8")
req.Headers.Add(HttpRequestHeader.CacheControl, "no-cache")
Dim statusCode As HttpStatusCode = Nothing
Try
Using result As HttpWebResponse = CType(Await req.GetResponseAsync(), HttpWebResponse)
statusCode = result.StatusCode
End Using
If statusCode = HttpStatusCode.OK Then
MsgBox("Valid")
Else
Dim response As String = New StreamReader(req.GetResponse().GetResponseStream()).ReadToEnd()
MsgBox(response)
End If
Catch webEx As WebException
MsgBox(New StreamReader(webEx.Response.GetResponseStream()).ReadToEnd())
End Try

Problem with Open method of MSXML2.ServerXMLHTTP.6.0 PATCH request

I have been using MSXML2.XMLHTTP.6.0 successfully with my Excel VBA script for a couple years, for both GET and POST requests. The POST request looks like:
Dim zipService as Object
Dim Query As String
Dim Body As String
Set zipService = CreateObject("MSXML2.XMLHTTP.6.0")
Query = "https://10.xxx.xxx.xxx:443/api/rest/v1/bulk/thresholdRules/"
zipService.Open "POST", Query, False
zipService.setRequestHeader "Authorization", "Basic " & gsUserIDPW
zipService.setRequestHeader "Content-Type", "application/json"
zipService.setRequestHeader "Accept", "application/xml"
Body = "Body of the request"
zipService.send (sBody)
Now I need to need to make a PATCH request to a new REST call for the same API. I have tested the PATCH REST call in Postman, and it works successfully. Using PUT in Postman also works. However, in Excel, when I try to do the Open call using PATCH (or PUT), the Open call fails with a -2147012891 error.
Any suggestions? Are PATCH and PUT allowed with the Open method? Are there other parameters I have to specify? All the code examples I find online are always GET and POST requests.

404 error while getting server response vb.net

I'm a totally beginner with webrequest, so I have no idea about what cause the error I get.
I try to login on a form following the microsoft tutorial for webrequest, but when I want to get the server response, I have the following error :
"the remote server returned an error (404) not found"
So I know that the URL I use actually exist and then wonder which part of the code is bad. Maybe it's because I'm doing an HTTPS request unlike the tutorial and it changes something ?
Also, I'm a little confused by getting directly the answer from the server : shouldn't there be kind of a trigger to know when the server answered ?
Dim request = WebRequest.Create("https://ssl.vocabell.com/mytica2/login")
request.Credentials = CredentialCache.DefaultCredentials
request.Method = "POST"
Dim byteArray = Encoding.UTF8.GetBytes("_username=x&_password=x")
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Dim dataStream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim reponse = request.GetResponse() 'ERROR
MsgBox(CType(reponse, HttpWebResponse).StatusDescription)
Using ds = reponse.GetResponseStream
Dim reader = New StreamReader(ds)
MsgBox(reader.ReadToEnd)
End Using
reponse.Close()
Thank you for your time, and if you have any relevant tutorial on the topic I would be glad to read it !
The page you've mentioned does exist and uses HTTPS, but if you look at the form tag within it, it's like this:
<form class="login-form form-horizontal" action="/mytica2/login_check" method="POST">
This means it doesn't post the form back to the same URL as the page, instead it sends it to the URL contained within that "action" attribute. If you're trying to use your code to simulate the submission of the login form then it looks like you need to send your POST request to https://ssl.vocabell.com/mytica2/login_check instead.

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

No response after authentication success in pentaho?

I try to use Basic Authentication to make a login into Pentaho by using .NET code
My code is:
Dim request = WebRequest.Create("http://x.x.x.x:8080/pentaho/Home")
Dim authInfo As String = Convert.ToString(userName) & ":" & Convert.ToString(userPassword)
authInfo = Convert.ToBase64String(Encoding.[Default].GetBytes(authInfo))
request.Headers("Authorization") = "Basic " & authInfo
Dim response As WebResponse = request.GetResponse()
You can see that I pass the authorization header with Basic username:password with Base64 encode.
for the last line of above code
Dim response As WebResponse = request.GetResponse()
you can see that I get the response from pentaho server then assign to variable response
In running, I found that Pentaho can return response and put the value to variable response.It seem okay that the authentication is passed and I login successfully
but when I input a link http://x.x.x.x:8080/pentaho/Home the login page still prompt and I need to login again....
Do you know what code I missing so that the Pentaho cannot login auto after above code?
Thanks you much!!!!!
Have you tried putting it as parameters in the url i.e :
?userid=joe&password=password
However, looking at it again it seems if you're successfully getting a logged in response, then the next request you are not logged in then you have not preserved the session/cookie between those two requests. Easily done in java with httpclient, not so sure about .net