While making an API call from swagger-ui, with content type "application/json", it is working fine. But when the same API is being called from below specified code, shows 404 StatusCode . What could be the possible reasons for it? Also, few other APIs from the same swagger-ui, are when being called from the code, they work from this same code.
var serialized = JsonConvert.SerializeObject(data);
String uri = GetEndpointUrl(path);
String responseData = "";
var buffer = System.Text.Encoding.UTF8.GetBytes(serialized);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
client.Timeout = TimeSpan.FromSeconds(120);
var response = client.PostAsync(uri, byteContent).Result;
responseData = await response.Content.ReadAsStringAsync();
Related
I recently moved into OKHTTP. I'm able to perform get request but while performing post i'm getting 404. Can someone help me out where I'm going wrong.
FYI:
auth token is correct & url is valid
public void PullRequest() throws IOException{
JSONObject jo = new JSONObject();
jo.put("head","patch-7");
jo.put("base","main");
MediaType JSON = MediaType.get("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, jo.toString());
//RequestBody body = RequestBody.create(jo.toString(),JSON);
Request request = new Request.Builder()
.url(url)
.header("Authorization",authorization)
.post(body)
.build();
Call call = httpClient.newCall(request);
Response response = call.execute();
if (response.code()>300) {
System.out.println("error...");
System.out.println(response.body().string());
}else {
System.out.println(response.body().string());
}
}
I am trying to attach files (screenshots) to an Azure DevOps work item via a C# desktop app. I have managed to attach files, but they're not valid image files, which leads me to believe that I'm doing something wrong in uploading them.
From the documentation DevOps Create Attachment below is the section on the Request body of the API call, which is rather vague.
From a GitHub discussion this answer seems to suggest that I just upload the binary content directly, which is what I'm doing.
My code is as follows
var img = File.ReadAllBytes(fname);
string query = #"/_apis/wit/attachments?fileName=" + fname + #"&api-version=6.0"
string response = AzureUtils.AttachFile(query, img, "POST", false, "application/octet-stream");
Is it correct that I literally pass in the byte array which is read from the file (variable img) as the body?
Why is it not a valid file when I look at it in DevOps?
The code for AttachFile is
public static string AttachFile(string query, byte[] data = null, string method = "GET",
bool dontUseBaseURL = false, string contentType = "application/json-patch+json")
{
try
{
HttpWebRequest request = WebRequest.Create(query) as HttpWebRequest;
request.ContentType = contentType;
request.Method = method;
request.Proxy.Credentials = CredentialCache.DefaultCredentials;
request.Headers.Add("Authorization", "Basic " +
Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{1}", ["AzurePAT"]))));
if (data != null)
{
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(data);
}
}
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
request = null;
response = null;
return result;
}
I'm trying to make a call to another microservice's get method from a service. But when I try to do so, I'm getting this error:
CS1503: Argument 2: cannot convert from ‘System.Net.Http.HttpContent’ to ‘System.Net.Http.HttpCompletionOption’.
Below is the code in the source microservice to get a list of data from the destination service.
this._httpClient.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "relativeAddress");
request.Content = new StringContent(JsonConvert.SerializeObject(invoiceFilterRequest),
Encoding.UTF8,
"application/json");//CONTENT-TYPE header
var response = await this._httpClient.GetAsync(InvEndpoints.GET_Cus_List, request.Content).ConfigureAwait(false);
Actual error is shown in the 2nd parameter request.Content in the GetAsync() call.
Here is the destination service method:
[HttpGet("cus/filter")]
public async Task<ActionResult<PagedList<Inv>>> GetCusByFilterAsync(InvFilterRequest request)
{
try
{
//..
}
}
Is there any simple solution to send object as a parameter using HTTP GET to another microservice other than sending them as a query string using the above code?
Please check the GetAsync(String, HttpCompletionOption) method, when using the GetAsync method, the second parameter should be the HttpCompletionOption, instead of HttpContent.
From your description, it seems that you want to send a request with parameters, if that is the case, you should use the HttpClient.PostAsync method, instead of the HttpClient.GetAsync method, refer the following sample:
var companyForCreation = new CompanyForCreationDto
{
Name = "Eagle IT Ltd.",
Country = "USA",
Address = "Eagle IT Street 289"
};
var company = JsonSerializer.Serialize(companyForCreation);
var requestContent = new StringContent(company, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync("companies", requestContent);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var createdCompany = JsonSerializer.Deserialize<CompanyDto>(content, _options);
Reference: Make HTTP requests using IHttpClientFactory in ASP.NET Cor
The API Method I am calling is:
[HttpPost("PostXml")]
[Consumes("application/xml")]
[Produces("application/xml")]
public Reservation PostXml([FromBody] Reservation res) =>
repository.AddReservation(new Reservation
{
Name = res.Name,
StartLocation = res.StartLocation,
EndLocation = res.EndLocation
});
The client code:
[HttpPost]
public async Task<IActionResult> AddReservationByXml(Reservation reservation)
{
Reservation receivedReservation = new Reservation();
using (var httpClient = new HttpClient())
{
StringContent content = new StringContent(ConvertObjectToXMLString(reservation), Encoding.UTF8, "application/xml");
using (var response = await httpClient.PostAsync("http://localhost:8888/api/Reservation/PostXml", content))
{
string apiResponse = await response.Content.ReadAsStringAsync();
receivedReservation = JsonConvert.DeserializeObject<Reservation>(apiResponse);
}
}
return View(receivedReservation);
}
string ConvertObjectToXMLString(object classObject)
{
string xmlString = null;
XmlSerializer xmlSerializer = new XmlSerializer(classObject.GetType());
using (MemoryStream memoryStream = new MemoryStream())
{
xmlSerializer.Serialize(memoryStream, classObject);
memoryStream.Position = 0;
xmlString = new StreamReader(memoryStream).ReadToEnd();
}
return xmlString;
}
I am failing to call the API method and getting the error:
400One or
more validation errors
occurred.https://tools.ietf.org/html/rfc7231#section-6.5.1|f5452728-4c49abe4d88e559e.1.8095e7c1_An
error occurred while deserializing input
data.
What is wrong here?
You got error from this line
receivedReservation = JsonConvert.DeserializeObject<Reservation>(apiResponse);
Please check the validation of your Reservation Model and detail the values you past
and the content of error you got.
Your XML request should be with the correct case as the c# class. XML is case sensitive.
Try this code.
XmlSerializer xsSubmit = new XmlSerializer(typeof(Reservation));
System.IO.StringWriter sww = new System.IO.StringWriter();
XmlWriter writer = XmlWriter.Create(sww);
xsSubmit.Serialize(writer, reservation);
var xml = sww.ToString();
I set my application to send a POST request with parameters to be passed in body using
qs.name = name; qs.id = id
request.AddJsonBody(qs)
But on running the application, i can see the individual parameters in my URL as query string parameters
If i Understand correctly you want to send a json a in the body for a post request, You Should use AddParameter(), Instead of AddJsonBody();
Here is a quick example
public IRestResponse ExamplePost(int id, string name)
{
object tmp = new
{
Id = id,
Name = name
};
string json = JsonConvert.SerializeObject(tmp);
var Client = new RestClient();
Client.BaseUrl = new Uri(YourEndPoint); //Your Url
var request = new RestRequest(Method.POST);
request.Resource = string.Format("/someurl");
request.AddParameter("application/json", json, ParameterType.RequestBody);
IRestResponse response = Client.Execute(request);
Logger.LogInfo($"Sending : {json}");
return response;
}
This will send the following json
{"Id":9939,"Name":"Zander"}