Hi I am trying to communicate with a webservice in my asp.net page in my code behind (vb.net) when i make the call I get a 401 unauthorised error however when i try the same call though a simple html page it works.
here is my simple html page
<form method="post" action="https://mycallingwebpage.co.uk/login">
<input type="submit">
</form>
this works fine and returns what i would expect.
however in my vb.net code this doesn't work.
Public Function mylogin(ByVal ServiceProfile) As String
Dim xmldoc As New Xml.XmlDocument
Try
myWebClient = New WebClient
myWebClient.Headers.Add("Content-Type", "text/plain")
Dim bytRetData As Byte() = myWebClient.DownloadData("https://mycallingwebpage.co.uk/login" & ServiceProfile)
Catch ex As Exception
End Try
End Function
I have now made some steps forward.
Further to my earlier question above i am still not able to make the call. I have found that if i make a call to the http url it works but calling the the https url it does not - this ajax call below does work for me - so effectively what do i need to do to convert this code below into a webclient call in vb.net? - this needs to work for https
$.ajax({
type: "POST",
contentType: 'application/x-www-form-urlencoded',
dataType: "application/xml",
crossDomain: true,
data: {'login' : encodeURIComponent('user'),'password' : encodeURIComponent('password')} ,
url: "https://myURL.com",
success: doThis,
error: doThat
});
you have to "authorize" yourself before accessing the WS. You are probably missing an Authorization header. Sorry, I'm not much of a VB expert, but it should be something like this:
myWebClient.Headers.Add("Authorization", "Basic " + ADD_UR_SECRET_HERE)
BTW, don't forget to encode your secret token using a Base64 Encoder before adding it to the headers.
Hope it helped.
Related
trying to send a POST to WCF services that accepts JSON string based on the website's JS. I had no luck buy just copy and paste the JSON string in an excel cell and use VBA's XMLHTTP60 to post. Always get bad data (status 400).
tried JSON string and JSON in cell doesn't work. I tried different JSON encoding doesn't seem to work either.
anyidea how I would post a JSON String to WCF?
My guess is somehow the VBA string loses its format during the request. Or different character code \ and : was send.
{"country":"{\"name\":\"USA\",\"population\":\"10000\"}\"}
{"country":"{"name":"USA","population":"10000"}"}
my VBA code
Sub test()
Dim XMLRequest As New MSXML2.XMLHTTP60
website = "URL"
postdata = thisworkbook.worksheets("Sheet1").range("A1").value
XMLRequest.Open "POST", "webSite", False
XMLRequest.SetRequestHeader "Content-Type", "application/json; charset=UTF-8"
XMLRequest.send postdata
end sub
However, I can use a browser console to send the AJAX with no problem.
var data=JSON.Stringify('{"country":"{"name":"USA","population":"10000"}"}');
$Ajax({
method: "POST",
URL: URL,
dataType:json,
contentType: "application/json; charset=UTF-8",
data:data,
cache: false
})
or I have no problem sending javascript in VBA via IE object
IE.Document.parentWindow.execScript "ajax call","javascript"
but my ultimate goal is to bypass IE, since it is not stable especially controlling through VBA.
In Django, I tried using form.errors.as_json() to get all form errors and here is sample json data strings.
{"password2":[{"message": "This password is too short. It must
contain at least 8 characters.","code":"password_too_short"}]}
I wanted to loop and get all under "message" key in json so I can use it to notify the user after ajax call.
Thanks
Anyways, I just resolved my issue and just wanted to share what I did.
views.py
if form.is_valid():
...
else:
# Extract form.errors
errMsg= None
errMsg = [(k, v[0]) for k, v in form.errors.items()]
return JsonResponse(errMsg)
Ajax Event
$.ajax({
method: "POST",
url: '\your_url_here',
data: $form.serialize(),
cache: false,
dataType: "json",
beforeSend: function(){
//Start displaying button's working animation
//Do some button or loading animation here...
}
},
success: function(jResults)
{
//This line is to remove field name display
var strErr = jResults + ''; //make json object as string
strErr = strErr.split(",").pop();
alert(strErr);
}
});
Hope this help to anyone out there facing similar issue. By the way, I'm using Django 2.0 and Python 3.6+
Thanks
MinedBP
The correct answer should be:
return HttpReponse(form.errors.as_json(), status=400).
In the AJAX call you can get the content doing:
`$.post("{% url 'your_url'%}", your_payload).done(function(data) {
do_something();
}).fail(function(xhr){
// Here you can get the form's errors and iterate over them.
xhr.responseText();
});`
You are sending a 200 HTTP response, that it is wrong, you should return a 400 HTTP response (Bad request), like Django do without AJAX forms.
I have an ajax call that works fine locally, but when I published it into the server, the code is never executed but returns "200 OK" anyway. No "success" code is ejecuted, nor the "error" code. Here's my ajax call:
$.ajax({
type: "POST",
url: "/CargadorContadores.aspx/ObtenerContadores",
contentType: "application/json; charset=utf-8",
data: "",
async: false,
dataType: "json",
success: function(data) {
var myObj = JSON.parse(data.d);
for (var i = 0; i < myObj.length; i++) {
var element = document.getElementById("LbItem " + myObj[i].MenuItemID);
element.innerHTML = "<b>" + element.innerHTML + " (" + myObj[i].Cantidad + ")</b>";
}
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
I also tried to put the complete url in the "url" field but still no luck.
The weird thing is that when I put the complete url directly into the browser, it is still not executing the code. And it works fine locally!!
I know there's a similar post (jQuery $.ajax failing silently, no error messages, and server responded with 200 OK) but is not resolved and it's driving crazy here.
PD: this is NOT cross-domain, my ajax code is in a .ascx and I am trying to call a method on an .aspx
Thanks very much!!!!
EDIT: I tried to remove the System.web.extensions reference of my web project and add the dll to my bin, but it's still not working (the 1.0.61025.0 version). Besides, I am running the ASP.NET website in IIS with framework 2.0, and I don't have framework 3.5 installed on my server (but locally I do). Maybe that's the problem? I can't install it because of the client security policies, what shall I do?
EDIT 2: I tried doing a simple response from my .aspx, just to test if the problem was in that method, but it is still not executing the success function. Here's my .aspx code:
[WebMethod]
public static string ObtenerContadores()
{
return new JavaScriptSerializer().Serialize("true");
}
and adapted the .ascx
$.ajax({
type: "POST",
url: "/CargadorContadores.aspx/ObtenerContadores",
contentType: "application/json; charset=utf-8",
data: "",
async: false,
dataType: "json",
success: function(dictionary) {
alert("hello");
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
Here's your problem: "The weird thing is that when I put the complete url directly into the browser, it is still not executing the code." Your JavaScript is expecting -- requiring -- a JSON response, and is apparently getting no response at all. This is not a JavaScript problem, but a problem with your .aspx page.
EDIT: Based on your comments below, it's clear that the problem is that your .aspx page is not returning what you expect. Because the .aspx doesn't produce the expected output even when you go to it directly, the problem is in that page, not in the jQuery.
Pretend the .aspx produces {}, false, or true. Your success code will run, but not do anything. Try putting an alert("Foo"); in there and watch what happens. The problem isn't that your jQuery is busted; it's that it isn't getting meaningful input from your .aspx page.
P.S. I would recommend using a variable name other than data in your success function, just in case it's getting messed up by the data object attribute in your .ajax call.
Okay, I believe I've figured this out, so I'm posting a second answer to preserve the prior discussion.
Here's the fix. Remove this line:
contentType: "application/json; charset=utf-8",
In my test script, this caused jQuery to send the Content-Type header application/json; charset=utf-8, as expected, but the actual contents of the request were not properly sent as JSON. For example, rather than sending {"foo":"bar"}, it was sending foo=bar. As a result, the receiving script acted as if no data was posted at all. When I commented out the line above, my test script worked fine and did whatever I expected with the values received from the target URL.
Note that this will post your data as normal post data. For example, if your $.ajax() call looks like this, the posted data will contain a variable named foo and one named who:
$.ajax({
...
data: {foo : "bar",
who : "what"},
...
});
If you want to post already-serialized JSON, do it like this:
$.ajax({
...
data: { somevariablename: '{"foo":"bar","who":"what"}' },
...
});
Then, you just have to parse the POST parameter somevariablename on the server side.
Hope this helps!
If its VS2012, try for adding Mime Type Handler, since VS2012 has IIS express and it need to add Mime type handler externally,
Add below code to web.config
<system.webServer>
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
</system.webServer>
.. and if its not VS2012 then follow this link
add .json handler support in IIS 7
I want to thank everyone for your help.
I finally had to install the 3.5 Framework on the server, I had no choice.
The second I installed it, and updated the web.config dll's references to 3.5, it worked like a charm.
Thanks again!!!!!
I'm trying to consume the json services from broadbandmap.gov so that I can display broadband providers and their speeds in an area. Here is a sample url:
http://www.broadbandmap.gov/internet-service-providers/70508/lat=30.1471824/long=-92.033638/%3Ejson
I'm using jquery to consume the service, however it's giving me an invalid label error in firebug:
var url = "http://www.broadbandmap.gov/internet-service-providers/70508/lat=30.1471824/long=-92.033638/%3Ejson";
//var url = "http://www.broadbandmap.gov/broadbandmap/broadband/fall2010/wireline?latitude=" + lat + "&longitude=" + long + "&format=json";
$.ajax({
url: url,
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (result) {
console.debug("in success");
console.debug(result);
//success, execute callback function.
},
error: function (result) {
console.debug("in error");
console.debug(result);
}
});
The strange thing is that under the Invalid Label error in Firebug it actually has the correct response:
{"status":"OK","responseTime":7,"messa...//www.cscic.state.ny.us/broadband/"}}}
I have tried setting the dataType to json, jsonp, and other types as well to no avail. I have also tried GET instead of POST but that didn't work either. Does anyone know what I'm missing?
That error is occurring because the service is returning JSON and not JSONP. Your browser is not going to let you process straight JSON from a cross-domain source.
In order to make the service return JSONP you have to use a specially formatted URL. If you go to the search results page without the "/>json" modifier (link) you'll see a link on the page that reads "API Call". If you hover over this link it will give you the correct URL to use for the wireless/wired API call. Use one of those URL's in your ajax call with a JSONP return type & callback and you should be all set.
I created an updated fiddle at http://jsfiddle.net/qsY7h/1/.
This is a cross-domain request so you should use JSONP datatype - the API supports this return type. The URL you provided in your example didn't return anything for me so I checked out Broadbandmap's Developer Docs and found an alternate call. Please find an example at http://jsfiddle.net/szCAF/.
The most important point to note is "callback=?" in the URL. jQuery uses this to tell the API what function name to wrap around the output (this is all done transparently by jQuery).
I know ODATA can return json but not sure if I have to use an attribute or interface to do so.
I want it to do just like http://odata.netflix.com/Catalog/Titles?$format=JSON but my odata service doesn't return JSON. When I call it like www.foo.com/service?$format=json, it just returns XML.
What do I need to do to return json with ODATA?
Download and install Fiddler.
http://www.fiddler2.com/fiddler2/
Once installed, open it, click on the "Request Builder" tab located in the right side of Fiddler.
Insert this URL:
http://test.com/feed2/ODataService.svc/results
Note that you DO NOT NEED THE ?$format=JSON
In the "Request Headers" section, insert the following line:
accept: application/json
Hit the Big "Execute" button at the top right of Fiddler.
You'll see the results of the request added to the list on the left side of Fiddler.
Double click on the request. The right side of Fiddler will change to the "Inspectors" tab where you can see the results of your request.
Also, since you are working with Json, you probably want to download and install the Json viewer plugin for Fiddler:
http://jsonviewer.codeplex.com/
Newer versions of WCF Data Services support JSON by default and you must have
Accept: application/json;odata=verbose
in the request header.
Accept: application/json
is no longer sufficient. More info here.
No-one seems to be answering your question very cleanly here!
From an HTML page you can use the following Javascript / JQuery code to have a WCF Data Service return data in JSON format;
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
var sURL = "http://YourService.svc/Books(10)";
function testJSONfetch() {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: sURL,
error: bad,
success: good,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
}
});
}
function good(response)
{
}
function bad(response)
{
}
</script>
You need to add “Accept: application/json” into the request header section.
Check out this link
If you're using the ODATA provider from Data Services you can easily return ODATA as JSON by specifying it in the URL as in the sample you gave - http://odata.netflix.com/Catalog/Titles?$format=JSON
To do this use the JSONp and URL-controlled format support for ADO.NET Data Services download from MSDN http://code.msdn.microsoft.com/DataServicesJSONP and add the JSONPSupportBehavior decorator to your DataService class like below.
[JSONPSupportBehavior]
public class MyDataService : DataService<MyContextType>
{
...
"...but I get "The webpage cannot be found" using http://test.com/feed2/ODataService.svc/results?$format=JSON ..."
you dont need the $format=JSON in the Uri.
Just use "http://test.com/feed2/ODataService.svc/results"
(with Accept: application/json in the request header)
Late answer, but I've been spending the last hour trying to figure out how to curl OData APIs and return the result as json. The following code fetches the document in json and writes it to a file:
-o myfile.html -H "Accept: application/json" http://example.com/api/data?$filter=name eq 'whatever'
... just use lower case letters:
"format=json"
It's not pretty but this is how I forced JSON output without using $format in the request string:
Request r = new Request(Method.GET, "http://XXXXXXX.svc//Login"
+ "&UserId=" + "'" + "user" + "'"
+ "&Password=" + "'" + "password" + "'");
ClientInfo ci = r.getClientInfo();
ArrayList<Preference<MediaType>> accepted = new ArrayList<Preference<MediaType>>();
accepted.add(new Preference<MediaType>(MediaType.APPLICATION_JSON));
ci.setAcceptedMediaTypes(accepted);
Client client = new Client(Protocol.HTTP);
Response response = client.handle(r);
Representation output = response.getEntity();