i'm trying to get a response from an httpwebrequest using get method and content type json..
but i'm getting Cannot send a content-body with this verb-type
here is my code:
Dim objRequest As HttpWebRequest = WebRequest.Create(url)
Dim reqBytes As Byte() = System.Text.UTF8Encoding.UTF8.GetBytes(strPost)
objRequest.Method = "GET"
objRequest.Timeout = "15000"
objRequest.ContentLength = reqBytes.Length
objRequest.ContentType = "application/json; charset=utf-8"
Try
myWriter = objRequest.GetRequestStream()
myWriter.Write(reqBytes, 0, reqBytes.Length)
Catch e As Exception
writetotext(e.toString)
End Try
am i missing something here?
HTTP GET cannot have a message body. Data gets typically passed through the URI path and query string and not through message body for GET requests. For POST, PUT, etc, you should be able to do what you are trying to do in the code above.
Related
When sending the request as a JSON, I get the error "Can't check the token validity." Previously, I obtained the token, which is stored in a variable. The statusCode: OK {200}.
What I observe with the error that is displayed is that the json cannot be sent because the token is not being validated. However, if I do the tests in Postman with the token and the JSON, the result is correct. I am using the RestSharp/106.15.0.0 library, which is the same one with which I obtained the token.
I have tried adding other lines of code, like
request2.AddBody(MyJson)
request2.AddHeader("Cache-Control", "no-cache")
I have carried out the tests in postman which are satisfactory
The code in VB.NET 2015 that I have developed is the following:
Dim client = New RestClient(Var_URLWS)
Dim request2 = New RestRequest(Method.POST)
request2.AddHeader("Content-Type", "application/json")
request2.AddHeader("Authorization", "Mybearer " & MyToken)
request2.AddJsonBody(MyJson, "application/json")
Dim response2 As RestResponse = client.Execute(request2)
I am having a hell of a time with this project I am working on and could really use your help. I'll try to keep this as concise as possible.
Basically, I have a UI setup that collects user information and sends REST API calls to my call control system. Currently it is working in regards to adding lines, trunks etc.
The problem is I want to see the body of the response coming back from the server. If I have the exception handling look for an OK status code and turn an indicator green, it performs as I have asked.
But I cannot get it to give me the full body of the response like it does when I send the call in POSTMAN.
Here is the response I get back in POSTMAN and would like to get back when I make the API call in VB. I get a Status Code 400 with this in the body.
{
"hint": "The specified Pattern (2952) is already in use by the line owner.",
"details": "Conflicting Pattern",
"code": "P0001",
"message": "invalid_parameter" }
I have tried every combination of search criteria I could find on this site and nothing seems to be working for me. I just don't know what I am doing wrong. Here is a sample of how the request/response is set up now.
Try
'//Setup HTTP connection and modify headers
Dim APIRequest As HttpWebRequest = HttpWebRequest.Create("https://" & CMIP.Text & "/api/v1/" & Custom_Endpoint_URL.Text)
APIRequest.Method = "POST"
APIRequest.Headers.Add("Authorization", "Bearer " + LatestToken.Text)
APIRequest.ContentType = "application/json"
'WebCall.Headers.Add("Prefer", "return=representation") 'Only used for testing purposes
'//Prepare JSON request
Dim bytearray As Byte() = System.Text.Encoding.UTF8.GetBytes(Custom_Body.Text)
APIRequest.ContentLength = bytearray.Length
'//Bypass self-signed cert issue
ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
'//Load JSON payload into datastream
Dim datastream As Stream = APIRequest.GetRequestStream()
datastream.Write(bytearray, 0, bytearray.Length)
''//Response
Dim response As WebResponse = APIRequest.GetResponse
Dim responsestream As Stream = response.GetResponseStream
Dim responsereader As New StreamReader(responsestream)
Dim responsereadstring As String = responsereader.ReadToEnd
'//Send response to results window
Response_Box.Text = responsereadstring
Catch ex As WebException
End Try
I wanted to figure this out on my own but I have been at this for a few days now and I'm at the point I am banging my head against the wall.
The HttpWebRequest.GetResponse method throws a WebException when the response has a status code in the 4xx or 5xx range. Based on the information in your question, your API call is returning a status code of 400, so that would trigger the exception. Your Catch block is completely empty, so you are silently ignoring this case. (That is why you should never leave your Catch blocks empty-- you'll never know that something is failing.)
It turns out that the WebException class has a Response property on it (as well as Status), so you can get the data from there. You just need to fill in the Catch block:
Catch ex As WebException
Dim responsestream As Stream = ex.Response.GetResponseStream
Dim responsereader As New StreamReader(responsestream)
Dim responsereadstring As String = responsereader.ReadToEnd
Response_Box.Text = responsereadstring
End Try
Similar to this question, I need to send back JSON.
WCF ResponseFormat For WebGet
But I'm working from within a WCF Behavior being called by a BizTalk 2010 SendPort Adapter.
I'm inside this method:
public object BeforeSendRequest(ref Message request, IClientChannel channel)
So I have the Message and the channel that I can manipulate.
I think the direction is something like this:
1) //WebOperationContext.Current.OutgoingResponse.ContentType = “text/plain”;
or
2) OperationContext.Current.... something - but I don't know the object model well.
I'm currently using the MemoryStream:
byte[] byteArrayJSON = Encoding.UTF8.GetBytes(strJSON);
MemoryStream memStreamJSON = new MemoryStream(byteArrayJSON);
//WebOperationContext.Current.OutgoingResponse.ContentType = “text/plain”;
Message newMessage = Message.CreateMessage(MessageVersion.None, "", memStreamJSON);
...
request = newMessage; // substitute my new message for the original one.
My headers have this:
Content-Type: application/json
Accept: application/json
I think these are the lines I need, but still testing...
WebBodyFormatMessageProperty bodyFormat = new WebBodyFormatMessageProperty(WebContentFormat.Json);
newMessage.Properties.Add(WebBodyFormatMessageProperty.Name, bodyFormat);
It looks like maybe now I should pass XML and this will cause the serialization to happen? I'm now on to my next error:
System.ArgumentException: Encountered unexpected namespace 'http://schemas.datacontract.org/2004/07/System.IO'. The namespace must be empty.
Parameter name: ns
Going to try "raw":
WebBodyFormatMessageProperty bodyFormat = new WebBodyFormatMessageProperty(WebContentFormat.Json);
newMessage.Properties.Add(WebBodyFormatMessageProperty.Name, bodyFormat);
I am using an online NLP API called Wit.ai. I am sending an http web request, and I get a response, and that all works perfectly fine. However, now I need to know how to POST this JSON:
{
"state": "email_or_text"
}
As an addition to this code:
Function getJson()
Dim editedText As String = TextBox1.Text.Replace(" ", "%20")
Dim myHttpWebRequest = CType(WebRequest.Create("https://api.wit.ai/message?v=20140609&q=" + editedText + "&units=metric"), HttpWebRequest)
myHttpWebRequest.Headers.Add("Authorization: Bearer <myauthcode>")
Dim myHttpWebResponse = CType(myHttpWebRequest.GetResponse(), HttpWebResponse)
Dim myWebSource As New StreamReader(myHttpWebResponse.GetResponseStream())
Dim myPageSource As String = myWebSource.ReadToEnd()
Return myPageSource
End Function
Thanks for your help!
Check this code at http://dotnetpad.com/9O883hmI
it has a quick example of a POST method that can get you started on posting your JSON.
Modify the URL and the content string and hit Run and see the results!
am getting rather frustrated at the lack of information out there on how to post data to a WCF REST method in JSON form. I have tried almost everything out there. Google is just returning purple links at this point...
What I am looking for is a way to send a JSON object to my method so it can shelve all of the data for me. What I am currently trying to get working is below:
The Method header:
[WebInvoke(Method = "POST", UriTemplate = "role/new", ResponseFormat = WebMessageFormat.Json)]
void AddNewRole(Stream streamdata)
The logic from the client app:
string json = JsonConvert.SerializeObject(role);
byte[] buffer = Encoding.UTF8.GetBytes(json);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://IP/InfoService/role/new");
request.Method = "POST";
request.Credentials = new NetworkCredential("", "");
request.ContentType = "application/x-www-form-urlencoded";
using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))
{
sw.Write(json);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
MessageBox.Show(sr.ReadToEnd());
}
Using this method I get an accepted response from the service, but it is a blank response and no new data gets added to the database. Granted, it is possible that there is a problem with my database update methods. Either way, can anyone help me figure out where I am going wrong?
EDIT: I now have fiddler able to test on the test client, and as expected there are problems with my DB queries. Ill post back soon.
EDIT2: Finally worked out the database problems, I have now successfully invoked through fiddler.
EDIT3: Its working now, thanks to nobody.
The code above has been edited, it works.