I'm trying to Upload apk file to our cloud via API.
When I'm test it on POSTMAN everything works fine,
but when I'm trying to convert it to PowerShell, it's not working at all.
Here is the relevant parameters on AJAX:
var form = new FormData();
form.append("app-data", "Netflix_v6.7.1_build_28752_apkpure.com.apk");
form.append("newVersion", "true");
form.append("Partver", "22222");
form.append("platformType", "ANDROID");
var settings = {
"async": true,
"crossDomain": true,
"url": "https://URL",
"method": "POST",
"headers": {
"authorization": "Basic CodeHere",
"cache-control": "no-cache",
"postman-token": "b581369a-98sas-a49d-231e-sddsadsadsaf2"
},
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
"data": form
}
$.ajax(settings).done(function (response) {
console.log(response);
});
My code:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("authorization", "Basic CodeHere")
$headers.Add("cache-control", "no-cache")
$headers.Add("postman-token", "b581369a-98sas-a49d-231e-sddsadsadsaf2")
$ori = "app-data"
$url = "https://URL"
$person = #{
"app-data" = "\\server\Netflix_v6.7.1_build_28752_apkpure.com.apk"
newVersion = 'true'
cmPartitionId = '22222'
platformType = 'ANDROID'
}
$body = (ConvertTo-Json $person)
Invoke-RestMethod -Uri $url -Headers $headers -Body $body -Method Post -ContentType "multipart/form-data"
Related
I am writing API tests using Cypress 6.4.0 & TypeScript where I need to upload a pdf file in the request body.
My code for the request is:
My code for the request body is:
public async createAssetDocTest() {
let url = sharedData.createAsset_url + sharedData.assetA;
let response = await fetch(url
,
{
method: 'POST',
body: await requestbody.createAssetDocBody(),
headers: {
Authorization: sharedData.bearer + " " + adminTokenValue,
Accept: sharedData.accept,
'Content-type': sharedData.docReqContent,
},
}
);
expect(response.status).to.equal(200);
public async createAssetDocBody(): Promise<any> {
const file = sharedData.doc;
cy.fixture(file).then((pdfDoc) => {
Cypress.Blob.binaryStringToBlob(
pdfDoc,
sharedData.contentTypeValue
).then(async (blob: string | Blob) => {
const formData = new FormData();
formData.set(sharedData.document, blob, file);
const body = {
formdata: {
document: {
value: pdfDoc,
options: {
filename: sharedData.document,
contentType: null,
},
},
},
};
return body;
});
});
}
However, the file does not upload the file & the request fails with error 400. Is there a better way to upload files in the body of the POST request?
enter image description here
Resolved this issue!
The main issue was that my Cypress version was too old. Upgraded to 9.7.0
Then added the following code:
public async createAssetDoc(): Promise<any> {
cy.fixture("pic location", "binary")
.then((file) => Cypress.Blob.binaryStringToBlob(file))
.then((blob) => {
var formdata = new FormData();
formdata.append("document", blob, "pic location");
const url = "your url";
cy.request({
url,
method: "POST",
body: formdata,
headers: {
Authorization:
"bearer" + " " + token,
Accept: "application/json",
"Content-Type": "multipart/form-data",
},
}).then((response) => {
expect(response.status).to.equal(201);
expect(response.statusText).to.equal(
sharedData.fileUploadStatusText
);
const finalResponse = String.fromCharCode.apply(
null,
new Uint8Array(response.body)
);
return finalResponse;
});
});
}
Im working on a project, where we try to exchange different parameters between the UI and a RestAPI via AJAX. The RestAPI defines how the data has to look:
I tried to solve it this way:
$(document).ready(function(){
$("#submit").click(function(){
var credentials = [
{user_name: $("#uname").val(),
password: $("#pwd").val()
}
];
alert(credentials);
$.ajax({
url:"../rest/user/login",
type:"POST",
data:JSON.stringify({credentials: credentials}),
success: function(){
window.location.href = "startrackhome.html";
},
error: function error(response){
try{
var json = JSON.parse(response.responseText);
if(typeof json.message === 'undefined'){
throw new Error("Response json has no message");
}
else{
alert(json.message);
}
}
catch(ex){
alert("unexpected error (code:" + response.status +")");
}
}
});
});
});
The alert shows this: [object Object]
And I always get an error message (error: 400), which means that I mus have made a mistake and I think the format I'm sendig is wrong but I dont know how to fix it.
I hope you can help me! :)
I made some changes to your code :
// credentials is an object
var credentials = {
user_name: $("#uname").val(),
password: $("#pwd").val()
}
alert(credentials);
$.ajax({
// check this url seems a bit off
url: "../rest/user/login",
type: "POST",
data: {
credentials: credentials
},
success: function() {
window.location.href = "startrackhome.html";
},
error: function error(response) {
try {
var json = JSON.parse(response.responseText);
if (typeof json.message === 'undefined') {
throw new Error("Response json has no message");
} else {
alert(json.message);
}
} catch (ex) {
alert("unexpected error (code:" + response.status + ")");
}
}
});
in my case it makes this request :
fetch("https://stackoverflow.com/posts/rest/user/login", {
"headers": {
"accept": "*/*",
"accept-language": "",
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"102\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Linux\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-requested-with": "XMLHttpRequest"
},
"referrer": "https://stackoverflow.com/posts/72620005/edit",
"referrerPolicy": "strict-origin-when-cross-origin",
"body": "credentials%5Buser_name%5D=test&credentials%5Bpassword%5D=test",
"method": "POST",
"mode": "cors",
"credentials": "include"
});
credentials[user_name]: test
credentials[password]: test
which seems good, if the server needs a json, you can stringify the credentials, which gives this paylaod :
credentials: {"user_name":"test","password":"test"}
I have the following test
let rxId = "";
let basketAuthToken = "";
let basketId = "";
let replacedBody = "";
cy.fixture(`payload/${ordersPostPayload}`).then((Body) => {
cy.readFile(`temp/resultIdFile.json`).then((resultIdFile) => {
Id = resultIdFile.lastSucceededRxId;
basketAuthToken = resultIdFile.baskets[0].authToken;
basketId = resultIdFile.baskets[0].basketId;
cy.log(`the value of the read value is ${Id}`);
replacedBody = JSON.stringify(Body).split(`$Id`).join(Id);
cy.writeFile(`temp/ordersPostPayload.json`, replacedBody);
cy.request({
method: "POST",
url: `https://***/ops/orders`,
headers: {
"Content-Type": "application/json",
Channel: "**",
"EsbApi-Subscription-Key": `****`,
"Accept-Language": `en-US`,
"basket-token": basketAuthToken,
"basket-id": basketId,
redirectUrl: "****/evaluate-payment",
cancelUrl: "****/evaluate-payment",
},
body: replacedBody,
failOnStatusCode: false,
}).then((response) => {
cy.writeFile("temp/result.json", response);
});
});
});
The request is sent to the backend. On cypress GUI the request is just fired once. but when I check the backend I can see two requests.
I have been battling for a few days to follow an article . This is not new to me but not my strong point.
Ive managed to get my http request working but I think I need to add auth to it. here is the code.
const axios = require('axios');
const host = 'https://search-data-ds-42456788224444444444444444.us-west-1.es.amazonaws.com';
const index = 'msgsdatastream';
const type = 'msgs';
const url = `${host}/${index}/${type}/`;
const headers = { 'Content-Type': 'application/json' };
exports.handler = async (event, context) => {
let count = 0;
for (const record of event.Records) {
const id = 1;
if (record.eventName == 'REMOVE') {
await axios.delete(url + id);
return 'Item removed';
} else {
const document = record.dynamodb.NewImage;
console.log('Adding document');
console.log(document);
await axios.put(url + id, document);
}
count += 1;
}
return `Successfully processed ${count} records.`;
};
This is inside my Lambda function
Here is the cloudwatch logs.
2021-02-05T12:52:05.386Z 13782564-f0fc-4a6d-892a-c00c9e880bd1 ERROR Invoke Error {
"message": "Request failed with status code 403",
"name": "Error",
"stack": "Error: Request failed with status code 403\n at createError (/var/task/node_modules/axios/lib/core/createError.js:16:15)\n at settle (/var/task/node_modules/axios/lib/core/settle.js:17:12)\n at IncomingMessage.handleStreamEnd (/var/task/node_modules/axios/lib/adapters/http.js:260:11)\n at IncomingMessage.emit (events.js:326:22)\n at endReadableNT (_stream_readable.js:1241:12)\n at processTicksAndRejections (internal/process/task_queues.js:84:21)",
"config": {
"url": "https://search-msgs-ds-rt5io3veb4k4m5vtglmg43frxu.us-east-1.es.amazonaws.com/msgsdatastream/msgs/1",
"method": "put",
"data": "{\"Area\":{\"S\":\"Lotus\"},\"id\":{\"S\":\"2\"},\"Name\":{\"S\":\"Romano\"}}",
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=utf-8",
"User-Agent": "axios/0.21.1",
"Content-Length": 59
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1
}
}
I am failing forward on this one. editing as I go along. Please could you direct me in how to resolve this?
Using expo, whenever I run a post request with a FormData object with an appended JSON and a image file, I get
"error": "Unsupported Media Type",
"message": "Content type 'application/octet-stream' not supported",
"path": "/visitas/",
"status": 415,
[…]
as a response from the backend (which runs Spring Boot), but whenever I replicate the request into a HTTP Client (Insomnia on this case) the request follow as it should, and I can retrieve and see the image back as I should.
Code
Visitas.js
[…]
async function startVisita(checkin) {
// Checkin contains file uri and some other things
try {
const location = await getLocation();
const formData = new FormData();
formData.append('object',
JSON.stringify({
longitude: location.coords.longitude,
latitude: location.coords.latitude,
checkin: new Date(),
loja: {id: loja.id},
})
);
// object gets filled accondingly
formData.append('imagecheckin', {
uri: checkin.uri,
name: 'imagem.jpg', // I know the image is .jpg
type: 'image/jpg',
});
// imagecheckin is a object inside formData (not a readStream as it normally would)
console.log(formData);
try {
const response = await fetch(`${Endpoint.baseAddr}${Endpoint.visitas}`, {
body: formData,
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + await AsyncStorage.getItem('jwt'),
},
})
.then(res => res.json());
console.log(response);
} catch (err) {
console.error('Erro ao postar a visita! Erro causado:', err);
console.log(err.res, err.response);
}
} catch (err) {
console.error('Erro ao criar a visita! Erro causado:');
console.error(err);
}
}
[…]
ControllerImagens.java
[…]
#PostMapping
public ResponseEntity<T> adicionarCheckin(
#RequestPart(name = "imagecheckin", required = true) MultipartFile file,
#RequestPart(name = "object", required = true) T objeto,
#RequestHeader("authorization") String token) {
// Calls constructors, validators and stuff
[…]
And the formdata I get from the log is
FormData {
"_parts": Array [
Array [
"object",
"{\"longitude\":-40.3097038,\"latitude\":-20.3758293,\"checkin\":\"2020-04-29T18:06:22.994Z\",\"loja\":{\"id\":1}}",
],
Array [
"imagecheckin",
Object {
"name": "imagem.jpg",
"type": "image/jpg",
"uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252Fproatend-f576a9db-3f86-4238-8677-3ebbd056f4ea/Camera/1f2192a7-fe81-40d1-8efd-9ff6a98a32a3.jpg",
},
],
],
}