Request method 'PUT' not supported StatusCode: 405 - java

I get this warning
2017-05-25 00:48:43.125 WARN 7104 --- [nio-8080-exec-4] o.s.web.servlet.PageNotFound : Request method 'PUT' not supported
in intelliJ when I'm trying to do an update from c# (Visual Studio). But when I'm doing that update from Java, it works.
update method in Java:
#RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public Proba update(#RequestBody Proba proba) {
System.out.println("Updating proba ...");
try{
probaRepository.update(proba.getIdProba(),proba);
} catch (Exception e){
e.printStackTrace();
}
return proba;
}
C# method
static async Task<string> UpdateProbaAsync(string path, Proba proba)
{
string res = null;
HttpResponseMessage response = await client.PutAsJsonAsync(path, proba);
if (response.IsSuccessStatusCode)
{
res = await response.Content.ReadAsStringAsync();
}
return res;
}
and here is how I call UpdateProbaAsync
var rezU = await UpdateProbaAsync("http://localhost:8080/concurs/probe", new Proba(9, "cautare comori UPDATE", "3-5 ani", 0));
var probeUpdate = await GetProbaAsync("http://localhost:8080/concurs/probe");
foreach (var proba in probeUpdate)
{
Console.WriteLine(proba.ToString());
}
this is what I get for HttpResponseMessage response
+ response {StatusCode: 405, ReasonPhrase: '', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Transfer-Encoding: chunked
Connection: close
Date: Wed, 24 May 2017 21:57:39 GMT
Allow: POST
Allow: GET
Content-Type: application/json; charset=UTF-8
}} System.Net.Http.HttpResponseMessage

I guess you are missing the attribute from the c#
[HttpPut] //or [HttpPost]
[Route("/{path}")]
async Task<string> UpdateProbaAsync(string path, Proba proba)
{
}
default is GET and you are trying to put onto a GET API

Related

Groovy Spring Contract DLS turns string into JSON

I have the following contract generating script:
VALID_JSON_STRING = '{}'
[
Contract.make {
name("insertSomething_ShouldReturnHttp200")
description("POST should do sth")
request {
method 'POST'
url REQUEST_URL
body(
value: VALID_JSON_STRING
)
headers {
contentType(applicationJson())
}
}
response {
status 200
headers { contentType(applicationJson()) } }
}
]
But it gets compiled to:
#Test
public void insertSomething_ShouldReturnHttp200() throws Exception {
// given:
MockMvcRequestSpecification request = given()
.header("Content-Type", "application/json")
.body("{\"value\":{}}");
// when:
ResponseOptions response = given().spec(request)
.post("...");
// then:
assertThat(response.statusCode()).isEqualTo(200);
assertThat(response.header("Content-Type")).matches("application/json.*");
}
Notice the .body("{\"value\":{}}"); here.
Instead it should be .body("{\"value\":\"{}\"}");. It should not convert the JSON-string to an actual JSON. How do I prevent this?
EDIT: It was labeled as a bug now: https://github.com/spring-cloud/spring-cloud-contract/issues/652

Calling a RESTful service on an external domain via JQuery

I'm trying to calling a Java RESTful service by an html page, but I always get errors like the below:
No 'Access-Control-Allow-Origin' header is present on the requested resource", 405 (Method Not Allowed)
My simplest Java code is:
#SuppressWarnings({ "unchecked", "rawtypes" })
#RequestMapping(value = "/prenotazioni/{id}", method = RequestMethod.POST)
public ResponseEntity<Prenotazione> updatePrenotazione(HttpServletResponse response, #PathVariable int id, #RequestBody Prenotazione obj) {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
try {
prenotazioneService.updatePrenotazione(id, obj);
} catch (Exception e) {
return new ResponseEntity(e.getMessage(), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<Prenotazione>(obj,HttpStatus.OK);
}
And the html code is:
$('#btnSalva').on('click', function(e){
//Creo la stringa JSON nel formato atteso dal servizio RESTful
var obj = '{"aula":{"id":' + $("#id_aula").val() + '},"id_utente":1,"data_inizio":"' + $("#datetimepicker1").data().DateTimePicker.date() + '","data_fine":"' + $("#datetimepicker2").data().DateTimePicker.date() + '"}';
var id = $("#id_evento").val();
var url = "http://localhost:8080/gestione_aule/prenotazioni/" + id;
//With $.post I've got error: No 'Access-Control-Allow-Origin
$.post( "http://localhost:8080/gestione_aule/prenotazioni/" + id, obj );
//With $.ajax I've got error: 405 (Method Not Allowed)
/*$.ajax({
url: "http://localhost:8080/gestione_aule/prenotazioni/" + id,
type: "POST",
crossDomain: true,
data: obj,
dataType: "jsonp",
success:function(result){
alert(JSON.stringify(result));
},
error:function(xhr,status,error){
alert(status);
}
});*/
/*$.postJSON = function(url, data, callback) {
return jQuery.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
'type': 'get',
'url': url,
'data': JSON.stringify(data),
'dataType': 'jsonp',
'complete': function(e){
alert("c " + e);
},
'success': function(e){
alert("s " + e);
},
'error': function(e){
alert("e " + e);
}
});
};
$.postJSON(url, obj, function(e){alert(e);});*/
});
I've tried:
with and without specify response header in java servlet
mapping PUT and POST method
using $.post $.ajax
setting dataType json and jsonp
and many other combinations :)
But anyone worked for me... any suggest please?
Note: as I wrote in the code with $.post I've got error: No 'Access-Control-Allow-Origin, with ajax I've got error: 405 (Method Not Allowed)
Thans
The problem here that CORS (cross domain support) has 2 types of request:
Simple - such as HEAD, GET and POST. POST with content-type: application/x-www-form-urlencoded, multipart/form-data or text/plain
The rest requests are called Preflight requests
Your CORS request is a Preflight one. In Preflight requests the browser fires 2 requests:
OPTIONS - asking the server to verify that the origin, method and additional headers are trusted
The actual request - in your case POST
To fix the issue your case, add a new mapping that will handle the OPTIONS request:
#RequestMapping(value = "/prenotazioni/{id}", method = RequestMethod.OPTIONS)
public void updatePrenotazione(HttpServletResponse response, #PathVariable int id) {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
response.addHeader("Access-Control-Allow-Headers", "accept, content-Type");
}

How can i get webservice XML with JavaScript

How can i use Java Script with HTTP Web service, this is the HTTP get request:
'GET /stockquote.asmx/GetQuote?symbol=string HTTP/1.1
Host: www.webservicex.net
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://www.webserviceX.NET/">string</string>'
i have found this Java on stack but i cannot get it working:
'$.get(
"somepage.php",
{paramOne : 1, paramX : 'abc'},
function(data) {
alert('page content: ' + data);
}
);'
The reason the code you found isn't working is that it's wrapped in single quotes and it depends on a third-party library called jQuery. If you link to jQuery from your page (and remove the single quotes around the jQuery string) and point to the right URL in the $.get method with the right parameters, it will probably work fine.
I completed this in C#
'Using System.Net;
Using System.IO;
public class GetData
{
public static string HTTP_GET(string Url, string Data)
{
string Out = String.Empty;
System.Net.WebRequest req = System.Net.WebRequest.Create(Url + (string.IsNullOrEmpty(Data) ? "" : "?" + Data));
try
{
System.Net.WebResponse resp = req.GetResponse();
using (System.IO.Stream stream = resp.GetResponseStream())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(stream))
{
Out = sr.ReadToEnd();
sr.Close();
}
}
}
catch (ArgumentException ex)
{
Out = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}",
}
catch (WebException ex)
{
Out = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message);
}
catch (Exception ex)
{
Out = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message);
}
return Out;
}
}
[System.Web.Services.WebMethod]
public static string getQuote()
{
XmlDocument quoteXML = new XmlDocument();
string strQuote = GetData.HTTP_GET("http://www.mywebservice/stockquote.asmx/GetQuote", "symbol=lloy.l");
return strQuote;
}'

How to avoid HTTP Status 415 when sending ajax request to the server?

I have an AJAX call that should return JSON document
function getData() {
$.ajax({
url: '/x',
type: 'GET',
data: "json",
success: function (data) {
// code omitted
}
});
}
My server side is very simple.
#RequestMapping(value = "/x", method = GET, produces = "application/json")
public #ResponseBody List<Employee> get() {
return employeeService.getEmployees();
}
But my request can't even get to the controller. The error is:
HTTP Status 415 - The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
How can I fix it?
add #Consumes("text/html") before your code in server side,
#Consumes("text/html")
#RequestMapping(value = "/x", method = GET, produces = "application/json")
public #ResponseBody List<Employee> get() {
return employeeService.getEmployees();
}

soap response encoding '?' characters in all strings instead of russian .Net proxy, Java server(?)

I generate proxy classes with wsdl.exe to request web-services, that are probably build at java platform. The problem is with encoding of response. I get '?' instead of russian letters.(for example '????26' instead of 'АН26')
I also use soapUI and everything works well there. I am not experienced at configuring .Net clients. So how I could determine and configure proper encoding for response. I already played with app.config as next:
I attach headers information here. I don't wee encoding info at responce headers...
request headers:
Accept-Encoding: gzip,deflate
Content-Type: text/xml;charset=UTF-8
SOAPAction: "urn:#DCSSci_ListFlight_5"
Content-Length: 641
Host: 109.73.1.66:23022
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
response headers:
HTTP/1.1 200 OK
Date: Thu, 06 Sep 2012 03:47:52 GMT
Server: Apache/2.2.10 (Linux/SUSE)
200 OKX-FidelXML-Version: 2.0
Content-length: 15464
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/xml
Solution:
public class TraceExtension : SoapExtension
{
Stream oldStream;
Stream newStream;
public override Stream ChainStream(Stream stream)
{
oldStream = stream;
newStream = new MemoryStream();
return newStream;
}
public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
{
return null;
}
public override object GetInitializer(Type WebServiceType)
{
return null;
}
public override void Initialize(object initializer)
{
}
public override void ProcessMessage(SoapMessage message)
{
switch (message.Stage)
{
case SoapMessageStage.BeforeSerialize:
break;
case SoapMessageStage.AfterSerialize:
newStream.Position = 0;
Copy(newStream, oldStream);
break;
case SoapMessageStage.BeforeDeserialize:
message.ContentType = "application/soap+xml; utf-8";
Copy(oldStream, newStream);
newStream.Position = 0;
break;
case SoapMessageStage.AfterDeserialize:
break;
}
}
void Copy(Stream from, Stream to)
{
TextReader reader = new StreamReader(from, System.Text.Encoding.GetEncoding("utf-8"));
TextWriter writer = new StreamWriter(to, System.Text.Encoding.GetEncoding("utf-8"));
writer.WriteLine(reader.ReadToEnd());
writer.Flush();
}
}
[AttributeUsage(AttributeTargets.Method)]
public class TraceExtensionAttribute : SoapExtensionAttribute
{
private int priority;
public override Type ExtensionType
{
get { return typeof(TraceExtension); }
}
public override int Priority
{
get { return priority; }
set { priority = value; }
}
}
And than just add
[TraceExtension()]
attribute for proxy invoke method
You can override GetWebResponse of your proxy and change the encoding
public class YourProxyClass : SoapHttpClientProtocol
{
protected override WebResponse GetWebResponse(WebRequest request)
{
var response = base.GetWebResponse(request);
response.Headers["Content-Type"] = "text/xml; charset=utf-8"; //<==
return response;
}
}

Categories

Resources