In JDK8, HttpURLConnection.java doesn't support PATCH method. But why? And how can I solve the problem if the server use PATCH method?
/* valid HTTP methods */
private static final String[] methods = {
"GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"
};
Related
I have 2 Web API Projects:
Api1 is a testing-Environment for the JavaScript Front-End, but has a API
Back-end(the default ValuesController), also for testing.
Api2 is the "true" Back-end, from which the Experimental JavaScript UI schould pull Data. For Testing, i use the default ValuesController here too, because, i want to have the same Output.
Status Quo
The Api1-UI can query the Data from the ValuesController of the own API
The Api2 returns the Correct Data(tested in Firefox and with Fiddler)
The Code
JavaScript Client:
var _load = function (url) {
$.ajax({
url: url,
method: 'GET',
accepts: "application/json; charset=utf-8",
success: function (data) {
alert("Success: " + data);
},
error: function (data) {
alert("Error :" + data);
}
});
};
WebApi Controller method:
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
Problem
The JavaScript UI of the experimental Front-End is not able to display, or even receive, the data from the API 2, which is, according to Fiddler, sent correct.
My first thought was, I am using the wrong Method, but i tried $.getJSON and $.ajax. But i always end up with an error. It just says statusText= "Error"
I don't get, why it can display Data from the own ApiController, but not from the "External"...
Thanks for any Help/Suggestions
You seem to be accessing data from X from a different domain Y using ajax. This seems to be a classic cross domain access issue.
You need to set Access-Control-Allow-Origin to value " * " in your response header.
Response.Headers.Add("Access-Control-Allow-Origin", "*")
There various ways you can solve this
defining this header in IIS
using a actionfilter attribute like below
FilterAttribute
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Response != null)
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
base.OnActionExecuted(actionExecutedContext);
}
}
Using Attribute on Controller Action
[AllowCrossSiteJson]
public Result Get(int id)
{
//return appropriate result
}
I want to return JSON data back to the client, in my web service method. One way is to create SoapExtension and use it as attribute on my web method, etc. Another way is to simply add [ScriptService] attribute to the web service, and let .NET framework return the result as {"d": "something"} JSON, back to the user (d here being something out of my control). However, I want to return something like:
{"message": "action was successful!"}
The simplest approach could be writing a web method like:
[WebMethod]
public static void StopSite(int siteId)
{
HttpResponse response = HttpContext.Current.Response;
try
{
// Doing something here
response.Write("{{\"message\": \"action was successful!\"}}");
}
catch (Exception ex)
{
response.StatusCode = 500;
response.Write("{{\"message\": \"action failed!\"}}");
}
}
This way, what I'll get at client is:
{ "message": "action was successful!"} { "d": null}
Which means that ASP.NET is appending its success result to my JSON result. If on the other hand I flush the response after writing the success message, (like response.Flush();), the exception happens that says:
Server cannot clear headers after HTTP headers have been sent.
So, what to do to just get my JSON result, without changing the approach?
This works for me:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void ReturnExactValueFromWebMethod(string AuthCode)
{
string r = "return my exact response without ASP.NET added junk";
HttpContext.Current.Response.BufferOutput = true;
HttpContext.Current.Response.Write(r);
HttpContext.Current.Response.Flush();
}
Why don't you return an object and then in your client you can call as response.d?
I don't know how you are calling your Web Service but I made an example making some assumptions:
I made this example using jquery ajax
function Test(a) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "TestRW.asmx/HelloWorld",
data: "{'id':" + a + "}",
dataType: "json",
success: function (response) {
alert(JSON.stringify(response.d));
}
});
}
And your code could be like this (you need to allow the web service to be called from script first: '[System.Web.Script.Services.ScriptService]'):
[WebMethod]
public object HelloWorld(int id)
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("message","success");
return dic;
}
In this example I used dictionary but you could use any object with a field "message" for example.
I'm sorry if I missunderstood what you meant but I don't really understand why you want to do a 'response.write' thing.
Hope I've helped at least. :)
I have an ASP.NET service that I'm access from a asxh file that returns a JSON string. The service works great except when accessed from our blog sub domain which is on a separate server. (blog.laptopmag.com)
Here is my jQuery
$.ajax({
type: "GET",
url: "http://www.laptopmag.com/scripts/service.ashx",
data: { "op": "get_products" },
dataType: "json",
success: function (data) {
alert(data);
}
});
and here is my ashx file
public class service : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string jsonStr = "{}";
string op = context.Request["op"];
// Process request
context.Response.ContentType = "application/json";
context.Response.Write(jsonStr);
}
public bool IsReusable {
get {
return false;
}
}
}
I've tried switching to a jsonp request, but must be doing something wrong because I can't get anything to pull back. Here is what I've tried.
and here is my jsonp attempt that doesn't seem to work when called from blog.laptopmag.com
$.getJSON('http://www.laptopmag.com/scripts/service.ashx?callback=ProcessRequest&op=get_products', function(json) {
console.log(json);
});
OK, I figured out what the problem was with my JSONP request thanks to the following post:
Jquery success function not firing using JSONP
The problem was that the request wasn't getting a response back in the expected format.
Now, my ashx file now looks like this:
public void ProcessRequest (HttpContext context) {
string jsonStr = "{}";
string op = context.Request["op"];
string jsonp = context.Request["callback"];
// Do something here
if (!String.IsNullOrEmpty(jsonp))
{
jsonStr = jsonp + "(" + jsonStr + ")";
}
context.Response.ContentType = "application/json";
context.Response.Write(jsonStr);
}
and the jQuery ajax request looks like this:
$.getJSON('http://www.laptopmag.com/scripts/service.ashx?callback=?&op=get_products', function(json) {
console.log(json);
});
Security restrictions prevent you from making cross-domain jquery ajax calls, but there are workarounds. IMO the easiest way is to create a page on your site that acts as a proxy and hit the page with your jquery request. In page_load of your proxy:
WebClient client = new WebClient ();
Response.Write (client.DownloadString ("your-webservice-url"));
Other solutions can be found by a quick Google search.
I am trying my best but cannot figure out why I do not get a sucesful response to such a simple web service; can you have a look at it tell me what do I miss, pls?
Each time only the error function is called and Fiddler says I have HTTP Response 500.
thanks!
Additional Notes:
I checked Fiddler and it says:
No web service found at: /JQuery-Recepie/Chapter16-Ajax/MyWebService.asmx. But WHY?!?
My WebService class:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class MyWebService : System.Web.Services.WebService {
public MyWebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
}
My JavaScript that is bound to a button's click event which calls the webservice:
function jqHelloCall(){
$.ajax({ type: "POST",
contentType: "application/json; charset=utf-8",
url: "MyWebService.asmx/HelloWorld",
data: "{}",
dataType: "json",
success: function(msg){
alert(msg==null);
alert(msg.d);
},
error: function(){
alert('error');
}
}); }
Use the Firebug in Firefox to see the response sent by IIS. In Firebug on the Net tab you can filter only the Ajax requests (XHR). Most certainly you will find all the details about server exception in the response body IIS will send back.
pencilCake : I checked Fiddler and it says: No web service found at: /JQuery-Recepie/Chapter16-Ajax/MyWebService.asmx. But WHY?!?
Because the web methods should be STATIC
[WebMethod]
public static string HelloWorld() {
return "Hello World";
}
add the scriptMethod attribute to your service method...
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld() {
return "Hello World";
}
I'm trying to call web service function via GET method using jQuery, but having a problem. This is a web service code:
[WebService(Namespace = "http://something.com/samples")]
[ScriptService]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class TestWebService : System.Web.Services.WebService {
[WebMethod]
public string Test2()
{
string result = null;
try
{
result = "{'result':'success', 'datetime':'" + DateTime.Now.ToString() + "'";
}
catch (Exception ex)
{
result = "Something wrong happened";
}
return result;
}
}
That's the way I call the function:
$.ajax({ type: "GET",
url: "http://localhost/testwebsite/TestWebService.asmx/Test2",
data: "{}",
contentType: "application/json",
dataType: "json",
error: function (xhr, status, error) {
alert(xhr.responseText);
},
success: function (msg) {
alert('Call was successful!');
}
});
Method is called successfully, but result string gets covered by XML tags, like this:
<string>
{'result':'success', 'datetime':'4/26/2010 12:11:18 PM'
</string>
And I get an error because of this (error handler is called). Does anybody know what can be done about this?
Enable ASP.NET ASMX web service for HTTP POST / GET requests
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string Test2()
{
[...]
}
Rule for json:
You can only access data from the same domain!
The only exception is when using jsonp (which is quite complicated to implement since there is no jsonp serializer in the .NET framework).
If your are using a standard web service (and not WCF) you can find guidance howto implement this here.
Make sure to add this to your ajax options:
contentType: "application/json; charset=utf-8"
Your overall request should look like this to get json back instead of XML:
$.ajax({ type: "GET",
url: "http://localhost/testwebsite/TestWebService.asmx/Test2",
data: "{}",
contentType: "application/json",
dataType: "json",
contentType: "application/json; charset=utf-8".
error: function (xhr, status, error) {
alert(xhr.responseText);
},
success: function (msg) {
alert('Call was successful!');
}
});
ScottGu has a full breakdown on what's required here, but it looks like the missing contentType in your case (that one drove me nuts for a while too).
You might try setting the ResponseFormat on your methods. See http://williamsportwebdeveloper.com/cgi/wp/?p=494 to see how they did it for JSON. It probably just defaults to XML.
You need to decorate the method with the ScriptMethodAttribute:
[WebService(Namespace = "http://something.com/samples")]
[ScriptService]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class TestWebService : System.Web.Services.WebService {
[WebMethod]
[ScriptMethod]
public string Test2()
{
[...]
}
}
This will ensure that the method returns JSON by default (the default value of ResponseFormat is Json).
Did you try WebInvokeAttribute, it has members that define Request & Response formats where you can set to WebMessageFormat.Json.
Something like:
[WebInvoke(UriTemplate = "ServiceName", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare,
Method = "POST")]
You can use http handler instead of
web service.
You can parse xml response with
javascript on the client.