How can I send the multipart file type request in flutter with specific requirements? - spring

Request which I need to send with post method
multipartFile = http.MultipartFile.fromBytes(
'supportDocuments', item.files.single.bytes!,
contentType: MediaType('application', 'pdf'));
request.files.add(multipartFile);
request.headers.addAll(headers);
request.fields["processRequestDto"] = jsonEncode(docRefDto);
How can I solve this issue?

Related

sending GET request via REST template with JSON request body getting failed with binding binding element must be a struct error?

I am trying to send a GET request using REST Template with a JSON request body, but the request is failing with error,
processing
failedorg.springframework.web.client.HttpServerErrorException$InternalServerError:
500 Internal Server Error: [code=400, message=binding element must be
a struct]
I have tried hitting the endpoint using the insomnia and the request is going through successfully, There I have put 2 headers
1. Content-Type - application/json
2. Authorization - Bearer ******
And the JSON body.
My code in spring boot looks like this.
ResponseEntity<String> responseObject = null;
String URL = "https://myurl/endpoint";
String requestBody = "{\"requestType\":\"status\"}";
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization","Bearer ***");
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity httpEntity = new HttpEntity<>(body,headers);
System.out.println(httpEntity+" httpEntity");
System.out.println(headers+" headers");
responseObject = restTemplate.exchange(URL, HttpMethod.GET, httpEntity, String.class);
The sout for httpentity and header looks like this
httpEntity
<{"requestType":"status"},[Authorization:"Bearer *******************", Content-Type:"application/json"]>
headers
[Authorization:"Bearer *************************", Content-Type:"application/json"]
Also when I am trying to send a request without the body to another endpoint using rest template, that is getting executed successfully, so I think something with the way I am sending the body has to do with the error.
rest template doesn't support get request with body . for more details you can refer this article.
If you are on Java 11 I would suggest you to use java.net.HttpClient which will fulfill your need.

Malformed request from aiohttp.ClientSession().post() with multiple image files

I'm still relatively new to Python and my first time to use aiohttp so I'm hoping someone can help spot where my problem is.
I have a function that does the following:
retrieves from the JSON payload two base64 strings - base64Front and base64Back
decode them, save to "images" folder
send the Front.jpg and Back.jpg to an external API
this external API expects a multipart/form-data
imgDataF = base64.b64decode(base64FrontStr)
frontFilename = 'images/Front.jpg'
with open(frontFilename, 'wb') as frontImgFile:
frontImgFile.write(imgDataF)
imgDataB = base64.b64decode(base64BackStr)
backFilename = 'images/Back.jpg'
with open(backFilename, 'wb') as backImgFile:
backImgFile.write(imgDataB)
headers = {
'Content-Type': 'multipart/form-data',
'AccountAccessKey': 'some-access-key',
'SecretToken': 'some-secret-token'
}
url = 'https://external-api/2.0/AuthenticateDoc'
files = [('file', open('./images/Front.jpg', 'rb')),
('file', open('./images/Back.jpg', 'rb'))]
async with aiohttp.ClientSession() as session:
async with session.post(url, data=files, headers=headers) as resp:
print(resp.status)
print(await resp .json())
The response I'm getting is status code 400 with:
{'ErrorCode': 1040, 'ErrorMessage': 'Malformed/Invalid Request detected'}
If I call the url via Postman and send the two jpg files, I get status code 200.
Hope someone can help here.
Thanks in advance.
Try using FormData to construct your request. Remove the content type from header and use it in FormData field as below:
data = FormData()
data.add_field('file',
open('Front.jpg', 'rb'),
filename='Front.jpg',
content_type='multipart/form-data')
await session.post(url, data=data)
Reference: https://docs.aiohttp.org/en/stable/client_quickstart.html#post-a-multipart-encoded-file

RestController PutMapping malformed url when using "[]"

I have a Spring App witch use a controller like this:
#PutMapping("/block/{blockid}/service/{serviceid}")
public ResponseEntity<String> config(#PathVariable blockid, #PathVariable serviceid, #RequestBody String body) {
{
And I using Postman to test the request, if i send this request to this url:
url: localhost:7000/block/myBlockTest/service/externalServiceTest[0]
Response this error:
Description The server cannot or will not process the
request due to something that is perceived to be a client error
(e.g., malformed request syntax, invalid request message framing, or
deceptive request routing).
I know the problem is "[0]" in the url.
Is there any way I can send this in the URL ?
Thanks.
OK, I just need modify the request to be localhost:7000/block/myBlockTest/service/externalServiceTest%5B0%5D
Special parameters.
https://cachefly.zendesk.com/hc/en-us/articles/215068626-How-to-format-URLs-that-have-special-characters-in-the-filename-

Bulk Import Request for FHIR

https://github.com/smart-on-fhir/bulk-import/blob/master/import.md
I used above link for reference and tried to run import using the following code
import requests
url = "https://<fhir-server-name>.azurehealthcareapis.com/$import"
payload = "{\r\n\t\"inputFormat\": \"application/fhir+ndjson\",\r\n\t\"inputSource\": \"https://localhost\",\r\n\t\"storageDetail\": { \"type\": \"https\" },\r\n\t\"input\": [\r\n\t{\r\n\t\t\"type\": \"Patient\",\r\n\t\t\"url\": \"https://localhost/patient_ndjson.ndjson\"\r\n\t}\r\n\t]\r\n}"
headers = {
'Accept': 'application/fhir+json',
'Prefer': 'respond-async',
'Content-Type': 'application/json',
'Authorization': 'Bearer <Auth Token>'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
i am receiving 400 Bad Request . i tried posting to both
url = "https://<fhir-server-name>.azurehealthcareapis.com/$import"
url = "https://<fhir-server-name>.azurehealthcareapis.com/Patient/$import"
I used apache for hosting the file and the file is accessible with both http and https.. Instead of importing it using http server, is there any way to directly point to my local ndjson file ?
patient_ndjson.ndjson contains
{"resourceType":"Patient","id":"8c76dfe7-2b94-497b-9837-8315b150ac0e","meta":{"versionId":"1","lastUpdated":"2020-04-27T11:08:10.611+00:00"},"active":true,"name":[{"use":"official","family":"p000001"}],"gender":"female","birthDate":"2020-04-27T11:00:00+05:30"}
{"resourceType":"Patient","id":"bfab05c7-d36a-4b5a-a0d6-6efb1da0fb3d","meta":{"versionId":"1","lastUpdated":"2020-04-27T11:34:43.83+00:00"},"active":true,"name":[{"use":"official","family":"p000001"}],"gender":"female","birthDate":"2020-04-27T11:00:00+05:30"}
{"resourceType":"Patient","id":"4c314eb1-6309-424b-affc-197fb0131cf6","meta":{"versionId":"1","lastUpdated":"2020-04-27T12:09:20.777+00:00"},"active":true,"name":[{"use":"official","family":"p000002"}],"gender":"female","birthDate":"2020-04-27T03:00:00+05:30"}
Can you please provide some sample request . it would be helpful.
$import is a draft spec and it is not supported (yet) on the Azure API for FHIR.

Cross domain put call does not work with Access-Control-Allow-Origin

I am facing problem related to cross domain PUT call , i have allowed Access-Control-Allow-Origin from server side put still it doesn't work.
#PUT
#Path("/getresponse/{caller}")
#Produces({MediaType.APPLICATION_JSON})
public Response getResponseData(#PathParam("caller") String caller ,#QueryParam("ticket")String ticket ,#FormParam("formParam") String data){
ResponseBuilder resp;
System.out.println("name of caller is -> "+ caller);
System.out.println("query param ticket -> "+ ticket);
System.out.println("form param data->" + data);
Employee emp = new Employee();
emp.setAge(23);
emp.setName("data");
Gson gson = new Gson();
String responseJson = gson.toJson(emp);
resp=Response.ok(responseJson);//header("Access-Control-Allow-Origin", "*")
resp.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS");
return resp.build();
}
whenever i call it from jquery ajax method it says
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
I have same replica of above service but with POST signature when i call that service it calls service without any problem
Post service code is
#POST
#Path("/getresponses/{caller}")
#Produces({MediaType.APPLICATION_JSON})
public Response getResponseData1(#PathParam("caller") String caller ,#QueryParam("ticket")String ticket ,#FormParam("formParam") String data){
ResponseBuilder resp;
System.out.println("name of caller is -> "+ caller);
System.out.println("query param ticket -> "+ ticket);
System.out.println("form param data->" + data);
Employee emp = new Employee();
emp.setAge(23);
emp.setName("data");
Gson gson = new Gson();
String responseJson = gson.toJson(emp);
resp=Response.ok(responseJson);//header("Access-Control-Allow-Origin", "*")
resp.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST");
return resp.build();
}
My client side code is
$(document).ready(function(){
// for post service
$('#sendcall').on('click',function(e){
var dataTosend ="formParam=data to send";
$.ajax({
url: 'http://someip:8099/Jqgrid/rest/getdata/getresponses/data?ticket=tick',
contentType : 'application/x-www-form-urlencoded',
data :dataTosend,
type: 'POST',
success: function(data){
alert(data);
}
});
});
//for PUT service
$('#sendcall2').on('click',function(e){
var datatosend ="formParam=data to send";
$.ajax({
url: 'http://someip:8099/Jqgrid/rest/getdata/getresponse/aliahsan?ticket=tick',
contentType : 'application/x-www-form-urlencoded',
data :datatosend,
type: 'PUT',
crossDomain:true,
beforeSend: function (xhr) {
console.log('header added');
},
success: function(data){
alert(data);
}
});
});
});
Please help me in this regard why PUT is not working with this.
Any help will be greatly appreciated
Instead of adding all the CORS headers inside your resource method, use a Jersey filter, as described in this post. The reason for this, is the CORS preflight request, which is defined in HTTP access control (CORS) as:
"preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send.
So the request is an OPTIONS request and it expects back the the "Accept-Xxx" CORS headers to determine what is allowed by the server. So putting the headers in the resource method has no affect as the the request is made with the OPTIONS HTTP method, which you don't have a resource method for. This generally leads to a 405 Method Not Allowed error sent to the client.
When you add the headers in the filter, every request goes through this filter, even the OPTIONS request, so the preflight gets the according headers.
As for the PUT, also described in the above linked document (continuing from the above quote)
Cross-site requests are preflighted like this since they may have implications to user data. In particular, a request is preflighted if:
It uses methods other than GET, HEAD or POST. Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted.
It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)
This is why the POST request doesn't face the same problem.

Resources