restassured returns 405 but postman returns 200 - http-status-code-405

public void testScriptLine() {
//useRelaxedHTTPSValidation();
String base_url = ...;
String url = Props.getProp(base_url) +
NameManagementEndPoints.GET_NAME_LIST;
String bearerToken = Props.getMessage("bearer_token");
Map<String, Object> body = new HashMap<>();
body.put("pageNum", 1);
body.put("pageSize", 10);
given().log().all().
headers(
"Authorization",
"Bearer " + bearerToken,
"Accept",
ContentType.JSON).
contentType(ContentType.JSON).
body(body).
when().
post(url).
then().log().all().
statusCode(200).
body("code", equalTo(0), "msg", equalTo("success"));
}
Trying to use post method, but got below result of 405 error, but this api is working fine with postman. And the get method works both with restassured and postman.
HTTP/1.1 405 Not Allowed
Server: nginx
Date: Fri, 22 Jul 2022 09:44:26 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 166
Connection: keep-alive
<html>
<head>
<title>405 Not Allowed</title>
</head>
<body bgcolor="white">
<center>
<h1>405 Not Allowed</h1>
</center>
<hr/>
<center>nginx</center>
</body>
</html>
Thanks in advance

Related

How to stop Spring MVC from automatically adding the "Content-Length: 0" header to HEAD responses?

I'm specifically trying to test the case where my application doesn't receive a Content-Length header from the server, so I've set up my code not to include that header, but for some reason Spring is including it anyway with a value of 0:
#RequestMapping(value = "/test", method = RequestMethod.HEAD)
public void headTest(HttpServletRequest request, HttpServletResponse response) {
response.addDateHeader("Date", System.currentTimeMillis());
response.addHeader("Accept-Ranges", "bytes");
response.addHeader("Content-Type", "video/mp4");
}
$ curl -I http://myserver.com:8600/test
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Date: Thu, 28 Jul 2022 01:05:11 GMT
Accept-Ranges: bytes
Content-Type: video/mp4
Content-Length: 0
How can I stop Spring from including this header?
Setting a header to null to effectively remove it from the response works for embedded Tomcat and might work for other servers:
response.setHeader("Content-Length", null);

pyopenssl send('GET / HTTP/1.0\r\n\r\n' doesn't returns 'HTTP/1.1 400 Bad Request\

I'm creating a SSL Connection using PyOpenSSL and the trying to make a GET call but i run into :
`'HTTP/1.1 400 Bad Request\r\nDate: Fri, 14 Jul 2017 20:04:51 GMT\r\nServer: Apache/2.4.18 (Ubuntu)\r\nContent-Length: 305\r\nConnection: close\r\nContent-Type: text/html; charset=iso-8859-1\r\n\r\n'
(Pdb) c
.. info: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
<hr>
<address>Apache/2.4.18 (Ubuntu) Server at ecdhe-server Port 443</address>
</body></html>`
The Code i have is as follows :
1) I create SSL Connection as follows :
client = socket()
if self._proxy:
client.connect((proxy, 8080))
else:
client.connect((host_name, port))
context = Context(self._ssl_version)
if self._ciphers:
context.set_cipher_list(self._ciphers)
ssl_connection = Connection(context, client)
if self._extension=='SNI':
ssl_connection.set_tlsext_host_name(host_name)
ssl_connection.set_connect_state()
ssl_connection.do_handshake()
self._session_ref = ssl_connection.get_session()
self._ssl_connection = ssl_connection
And then call the get() function which is as follows:
def get(self, http_version='1.0'):
#self._ssl_connection.sendall("GET / HTTP/1.1\r\n\r\n")
self._ssl_connection.sendall("GET / HTTP/1.0\r\n\r\n")
response_contents = self._ssl_connection.recv(4096)
return response_contents
I tried all combinations of sendall and send(also i think) but i run into :
.. info: HTTP/1.1 400 Bad Request
Date: Fri, 14 Jul 2017 20:19:13 GMT
Server: Apache/2.4.18 (Ubuntu)
Content-Length: 305
Connection: close
Content-Type: text/html; charset=iso-8859-1
I would appreciate if some one would help out in resolving the issue.

Sendind files to web servicce : HTTP Error 415 Unsupported media type

I try from my rest client to send files to my web service but i keep getting 415 when i'm sure of the media type i'm sending.
I'm using spring MVC :
Here code of the rest client :
public Response uploadFile(FormDataMultiPart multipart, ...) {
WebTarget target = client.target(uri);
Response response = target.
path(*path*).
request().
header("Content-Type", "multipart/form-data").
post(Entity.entity(multipart, MediaType.MULTIPART_FORM_DATA), Response.class);
return response;
}
And here how i use my function :
#RequestMapping(value = "*map path*", method = RequestMethod.POST)
public ModelAndView saveAttachedFiles(#RequestParam("file") MultipartFile myFile, Model model, HttpServletRequest request) {
try {
File file = new File( myFile.getOriginalFilename());
myFile.transferTo(file);
FileDataBodyPart filePart = new FileDataBodyPart("file", file);
FormDataContentDisposition contentDisposition = FormDataContentDisposition.name("file").fileName(file.getName()).build();
filePart.setContentDisposition(contentDisposition);
FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
formDataMultiPart.bodyPart(filePart);
Response reponse = clientRest.uploadFile(formDataMultiPart, ...);
}
Here request header of my client (from logs)
31 > POST ***
31 > Content-Type: multipart/form-data
31 > Cookie: $Version=1;JSESSIONID=***
31 > Referer: ***
--Boundary_1_523348906_1460533877988
Content-Type: image/jpeg
Content-Disposition: form-data; filename="Penguins.jpg"; name="file"
Here code of the web services
#POST
#Path("/file")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormDataParam("file") InputStream fileInputStream,
#FormDataParam("file") FormDataContentDisposition contentDispositionHeader,
#QueryParam("uuid") String uuid) {
AttachedFileDto attachedFileDto;
try {
** Processing the file **
}
}
And the web service response header
31 < 415
31 < Access-Control-Allow-Credentials: true
31 < Access-Control-Allow-Headers: Content-Type, Accept, X-Requested-With,Cache-Control,Pragma
31 < Access-Control-Allow-Methods: GET,POST,HEAD,OPTIONS,PUT,DELETE
31 < Access-Control-Allow-Origin: http://localhost:3333
31 < Connection: Keep-Alive
31 < Content-Length: 0
31 < Content-Type: application/json
31 < Date: Wed, 13 Apr 2016 07:51:16 GMT
31 < Keep-Alive: timeout=5, max=100
31 < Server: Apache
Do you have any clue ?
Thanks =)
Found the solution to my problem, i was confused between PathParam and QueryParam.
Service was like this :
#FormDataParam("file") InputStream fileInputStream,
#FormDataParam("file") FormDataContentDisposition contentDispositionHeader,
#QueryParam("uuid") String uuid)
And i was putting my uuid parameter in path function :
public Response uploadFile(FormDataMultiPart multipart, ...) {
WebTarget target = client.target(uri);
Response response = target.
path(*path*?uuid=12315465).
request().
header("Content-Type", "multipart/form-data").
post(Entity.entity(multipart, MediaType.MULTIPART_FORM_DATA), Response.class);
return response;
}
Added the queryParam function :
public Response uploadFile(FormDataMultiPart multipart, ...) {
WebTarget target = client.target(uri);
Response response = target.
path(*path*).
queryParam("uuid", uuid).
request().
post(Entity.entity(multipart, multipart.getMediaType()));
return response;
}
And now it works =)

Post request to golang server using polymer core-ajax?

I am trying to make a POST request using polymer core-ajax to server runnung golang. After a lot of search (because i am new to this stuff) i ended up with the following code. Also, GET request is working perfect. POST parameters i dont understand how to pass using core-ajax.
<polymer-element name="register-user" attributes="url">
<template>
<core-ajax id="ajaxSubmit" url="{{url}}" contentType="application/json" handleAs="json" method="post" on-core-response="{{response}}"></core-ajax>
<style type="text/css">
</style>
</template>
<script>
Polymer({
buttonListener: function() {
var data = '{"Name":"'+ this.name +'", "Email":"'+ this.email +'"}';
this.$.ajaxSubmit.data = data;
this.$.ajaxSubmit.go();
console.log(data);
},
response: function(oldValue){
console.log(this.response);
}
});
</script>
</polymer-element>
above code returns 500 (Internal Server Error) however when i make a POST request using curl i.e
curl -i -H 'Content-Type: application/json' -d '{"Name":"Batman",
"Email":"batman#gmail.com"}' http://so.me.ip.ad:8080/register
it works as it should and returns
HTTP/1.1 200 OK
Content-Type: application/json
X-Powered-By: go-json-rest
Date: Wed, 29 Apr 2015 05:40:15 GMT
Content-Length: 117
{
"id": 3,
"name": "Batman",
"email": "batman#gmail.com",
"createdAt": "2015-04-29T05:40:15.073491143Z"
}
also, i have a CORS middleware set up on server i.e
api.Use(&rest.CorsMiddleware{
RejectNonCorsRequests: false,
OriginValidator: func(origin string, request *rest.Request) bool {
return origin == "http://0.0.0.0:8000"
},
AllowedMethods: []string{"GET", "POST", "PUT"},
AllowedHeaders: []string{
"Accept", "Content-Type", "X-Custom-Header", "Origin"},
AccessControlAllowCredentials: true,
AccessControlMaxAge: 3600,
})
What am i doing wrong? Any feedback will be of great help! Thanks ^.^
Edit : here is a little more info if it can help..
I think CORS is a red herring. The problem may be that you are sending the data form-encoded and not as json. I found a bug from a user with a similar problem.
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
X-Powered-By: go-json-rest
Date: Fri, 12 Dec 2014 04:29:59 GMT
Content-Length: 71
{
"Error": "invalid character '\\'' looking for beginning of value"
}
Perhaps you should use .body instead of .data? See this answer.
From the polymer documentation:
body: Optional raw body content to send when method === "POST".
Example:
<core-ajax method="POST" auto url="http://somesite.com"
body='{"foo":1, "bar":2}'>
</core-ajax>

WebApi 2.1 PUT throw error 415

I'm trying to update data using WebApi PUT method. My code working fine before, but suddenly I start to get this error.
"Message":"The request contains an entity body but no Content-Type header. The inferred media type 'application/octet-stream' is not supported for this resource.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'xEmployee' from content with media type 'application/octet-stream'.","ExceptionType":"System.Net.Http.UnsupportedMediaTypeException".
This is headers:
Response Header.
HTTP/1.1 415 Unsupported Media Type
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
Set-Cookie: Role=D65520F37D105E39C1A92C15CD482E378F32A769592AC7D8305285A5B9B90362F7F2F13F14E6DC220E44D26940B06B52E7460EF13184F245805AF9523D1072464F4BD06AFB4F8AEB8B7D8BF607A8922C6041A3A4C636BF3B26388E606A94FE43; expires=Tue, 07-Oct-2014 09:49:56 GMT; path=/
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 07 Oct 2014 09:19:56 GMT
Content-Length: 809
Request Header:
PUT /api/xemployees/2110481232 HTTP/1.1
Host: guideonline.ilvestour.office
Connection: keep-alive
Content-Length: 229
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://guideonline.ilvestour.office
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
Content-Type: application/json; charset=UTF-8"
Referer: http://guideonline.ilvestour.office/account
Accept-Encoding: gzip,deflate,sdch
Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: .ASPXAUTH=215C424A0A023F5B42775B7A73B08FEC8CB36E7200FBA430EADF2F300A84500571F8B5EE980C3EF2913FE160978973CDBC50BDD216E16FC342EF0B566D0944ECFD901DF471DEF9F6E5D272B52F2450CC0A1FB96BCC6B3B6E7A7C07343D4DFBD66; Role=DE678EE89D7089B8CD74B202E00C53CA9AE9E4C40B506C5C4EEF56E7962F38ED86F6BFD34E5FD3A6DD6ECCCF61AF768CAB0C1D7C5F15A8638F9454B24DF3208F021EB638235420574C6420CA5A19F0B6BD07BAC303FF79612D6C1AF246563A7
Request Payloadview source
{"Kod":2110481232, "Сотрудник": "Lena", "Telephon": "088-6734227", "Password":"rimosa57", "email":"samoylova-elena#mail.ru", "CrWho":"OMEGA.Administrator", "CrWhen":"2014-10-07T09:20:05.735Z"}
Nothing special in Controller code:
[Authorize(Roles = "Admin, User")]
public async Task<IHttpActionResult> PutxEmployee(int id, xEmployee xEmployee)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != xEmployee.Kod)
{
return BadRequest();
}
try
{
var user = db.xEmployee.Find(id);
user.Сотрудник = xEmployee.Сотрудник;
user.Telephon = xEmployee.Telephon;
user.Password = xEmployee.Password;
user.email = xEmployee.email;
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!xEmployeeExists(id))
{
return NotFound();
}
else
{
throw;
}
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
var path = "C:/error.txt";
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
}
using (StreamWriter sw1 = File.CreateText("C:/error1.txt"))
foreach (var ve in eve.ValidationErrors)
{
sw1.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
return StatusCode(HttpStatusCode.NoContent);
}
Same as WebApiConfig:
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.Culture = new CultureInfo("ru-RU");
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
There seems to be a typo (last ") in the request's Content-Type header:
Content-Type: application/json; charset=UTF-8"
When this header is missing or malformed, the server will automatically use application/octet-stream by default, as described by this post.
I were facing similar problem. Though i have a Content-Type declare it was still sending same error.
What I did is added Accept Header and it started working.
Accept: application/json
Content-Type: application/json
Also, make sure there's only one header Content-Type. In my case, my rest client was implicitly sending the empty Content-Type which got overridden by Content-Type: application/json hence the error.

Resources