We are trying to make an HTTPS POST request from ESP8266 to aws cloud but unable to communicate to the server.
The code snippet is given below:
WiFiClientSecure client;
char data[100];
DynamicJsonBuffer jsonBuffer;
char host[] = "test.execute-api.us-east-1.amazonaws.com";
if (client.connect(host, 443)) {
String URL = "/dev";
JsonObject& root = jsonBuffer.createObject();
root["Id"] = 105132;
sprintf(data, "{\"Id\":105132}");
client.println("POST " + URL+ " HTTP/1.1");
client.print("Host: " + (String)host);
client.println("User-Agent: arduino/1.0");
client.println(data);
client.println("Content-Type: application/json");
}
The working postman request given below:
URL : https://test.execute-api.us-east-1.amazonaws.com/dev
Header : Content-Type : application/json
Body : {"Id" : 105132 }
Related
hiii, This is for Sending HTTPS POST request to clould function server by using sim800l gprs module.the main problem is its could not send the data to server but its connects the server and its shows bad request 400.I can't understand the problem.the code will be given below.i use NODEMCU-32S micro controller.
SerialMon.println("Performing HTTP POST request...");
String httpRequestData = String(requestBody) +"";
client.print(String("POST ") + resource + " HTTP/1.1\r\n");
client.print(String("Host: ") + server + "\r\n");
client.println("Connection: close");
client.println("Content-Type: application/json");
client.print("Content-Length: ");
client.println(httpRequestData.length());
client.println();
client.println(httpRequestData);
timeout = millis();
while (client.connected() && millis() - timeout < 10000L) {
while (client.available()) {
char c = client.read();
SerialMon.print(c);
timeout = millis();
}
}
enter image description here <--this is the output image.
please help me to find out the solution.
This is happening because of cloudflare protection on server's end.
Things you can try
Download Cloudflare SSL from your account in your system before doing request
Disable cloudflare end to end SSL verification
Make request from https to https via connecting your Esp32 to a static IP
Why do I get this error "content-type of request should be application/json", because I encoded it application/json?
How to correct it?
In Postman the request is working fine.
int id = 208;
MediaType JsonType = MediaType.parse("application/json");
OkHttpClient client = new OkHttpClient();
String jsonBody = "{\"params\":[\"wandelnet\"," + id + "]}";
RequestBody body = RequestBody.create(jsonBody, JsonType);
Request request = new Request.Builder()
.url( "https://wandelnet.api.routemaker.nl/routemaker/getPublishedRoute")
.post(body)
.addHeader("Content-Type", "application/json; charset=utf-8")
.addHeader( "Accept", "application/json")
.build();
Response response = client.newCall(request).execute();
The result is:
{"result":null,"error":{"code":"sherpaBadRequest","message":"content-type
of request should be application/json"}}
Try creating the request body from bytes, not from a string:
RequestBody body = RequestBody.create(jsonBody.getBytes(“UTF-8”), JsonType);
OkHttp automatically adds a charset when it does string encoding, and we need to prevent this here.
You’ll also want to omit the Content-Type header in your request builder.
To make SOAP HTTPS call I write this method in jRuby.
def run host, port, path, soap_request_file,password,protocol = "HTTP"
soapMsg = ""
request = ""
soap_request_file = Expertus::TestDataFile::get_file_relative_to_script(soap_request_file)
soapMsg = IO.read(soap_request_file)
request = "POST #{path} #{protocol}/1.1\r\n"
request = request + "Content-Type: text/xml;charset=UTF-8\r\n"
request = request + "Accept-Encoding: gzip,deflate\r\n"
request = request + "Content-Type: application/soap+xml\r\n" if soapMsg.downcase.include?("soap-envelope")
request = request + "Content-Length: #{soapMsg.length}\r\n"
request = request + "Authorization: Basic #{password}\r\n"
request = request + "\r\n"
request = request + soapMsg
request = request + "\r\n"
log.debug("Trying to connect to SOAP service on #{host}:#{port}")
# Sending request
socket = TCPSocket.open(host,port)
log.debug("Sending request to SOAP service")
log.debug("#{request}")
socket.send(request, 0)
# Reading response
log.debug("Reading SOAP service response")
response = socket.read
headers,body = response.split("\r\n\r\n", 2)
log.debug("Received SOAP service response headers #{headers}")
log.debug("Received SOAP service response body #{body}")
log.debug("Closing SOAP service connection")
socket.close
log.debug("Connection with SOAP service closed")
return headers,body
end
When I make HTTP call, I get correct response back : Received SOAP service response headers HTTP/1.1 200 OK
but when I make HTTPS call, I get "Received SOAP service response headers §♥♥ ☻☻P".
Am I missing something ?
I want to upload a image to the file system. So I am using Multi-part file upload with spring boot. And also I am using Advance Rest Client(Chrome) tool to POST Multi part file. But I am facing an error even I do not specify any content type org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found.
Here my rest controller code,
#RestController
public class StringController {
#RequestMapping(value="/upload", method=RequestMethod.POST)
public #ResponseBody String singleSave(#RequestParam("file") MultipartFile file){
String fileName = null;
if (!file.isEmpty()) {
try {
fileName = file.getOriginalFilename();
byte[] bytes = file.getBytes();
BufferedOutputStream buffStream =
new BufferedOutputStream(new FileOutputStream(new File("F:/" + fileName)));
buffStream.write(bytes);
buffStream.close();
return "You have successfully uploaded " + fileName;
} catch (Exception e) {
return "You failed to upload " + fileName + ": " + e.getMessage();
}
} else {
return "Unable to upload. File is empty.";
}
}
}
Screenshot (Advance rest client tool)
Error
{
"timestamp": 1490678908517,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.web.multipart.MultipartException",
"message": "Could not parse multipart servlet request; nested exception is java.io.IOException: org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found",
"path": "/upload"
}
The problem is in your request from advance rest client. It is working fine in the postman.The image is getting uploaded. Try with postman you will get it.
You lost in you client request headers value boundary.
Construct in PostMan header "Content-Type" like this:
Content-Type : multipart/form-data;boundary="12312313132132"
If the response from server is a redirection i.e. a 302 status with location header , Jetty's ProxyServlet does not handle that and the control redirects to original server . How can i resolve this ? Also how can i change the Response and Response headers ?
You can override a method in ProxyServlet that lets you rewrite headers. So you can, for example, see if there is a Location header, and if so remove the target URL and replace it with the URL that the client requested. This is how I did it:
#Override
protected String filterServerResponseHeader(HttpServletRequest clientRequest, Response serverResponse, String headerName, String headerValue) {
if (headerName.equalsIgnoreCase("location")) {
URI targetUri = serverResponse.getRequest().getURI();
String toReplace = targetUri.getScheme() + "://" + targetUri.getAuthority();
if (headerValue.startsWith(toReplace)) {
headerValue = clientRequest.getScheme() + "://" + clientRequest.getHeader("host")
+ headerValue.substring(toReplace.length());
log.info("Rewrote location header to " + headerValue);
return headerValue;
}
}
return super.filterServerResponseHeader(clientRequest, serverResponse, headerName, headerValue);
}