Actionscripts 3 POST JSON with Content Header - actionscript-3

I'm trying to post JSON to server but code not working. I found some example to post JSON with Actionscripts 3 but i need to define content type in code. i post my test code here.
I tested url+header+body in firefox RESTClient and they working.
[![enter image description here][1]][1]
I'm sure URL is true and working in another places but here i got error "Error opening URL"
URL:"https://api.thinger.io/v2/users/***"
Content Header: "application/json"
Body: {"in":true}
import flash.display.Sprite;
import flash.events.*;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLRequestHeader;
import flash.net.URLRequestMethod;
import flash.net.URLVariables;
var loader: URLLoader;
function ATN() {
loader = new URLLoader();
configureListeners(loader);
var header: URLRequestHeader = new URLRequestHeader("Accept", "application/json");
var request: URLRequest = new URLRequest("https://api.thinger.io/v2/users/***");
request.data = new URLVariables("in:true");
request.method = URLRequestMethod.POST;
request.requestHeaders.push(header);
try {
loader.load(request);
} catch (error: Error) {
trace("Unable to load requested document.");
}
}
function configureListeners(dispatcher: IEventDispatcher): void {
dispatcher.addEventListener(Event.COMPLETE, completeHandler);
dispatcher.addEventListener(Event.OPEN, openHandler);
dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
}
function completeHandler(event: Event): void {
var loader: URLLoader = URLLoader(event.target);
trace("completeHandler: " + loader.data);
}
function openHandler(event: Event): void {
trace("openHandler: " + event);
}
function progressHandler(event: ProgressEvent): void {
trace("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal);
}
function securityErrorHandler(event: SecurityErrorEvent): void {
trace("securityErrorHandler: " + event);
}
function httpStatusHandler(event: HTTPStatusEvent): void {
trace("httpStatusHandler: " + event);
}
function ioErrorHandler(event: IOErrorEvent): void {
trace("ioErrorHandler: " + event);
}
ATN();
ERROR:
Error: Error #2101: The String passed to URLVariables.decode() must be
a URL-encoded query string containing name/value pairs.
at Error$/throwError()
at flash.net::URLVariables/decode()
at flash.net::URLVariables()
at ATN_fla::MainTimeline/ATN()
at ATN_fla::MainTimeline/frame1()
EDIT:
function ATN() {
loader = new URLLoader();
configureListeners(loader);
var header: URLRequestHeader = new URLRequestHeader("Accept", "application/json");
var request: URLRequest = new URLRequest("https://api.thinger.io/v2/users/***");
request.data = new URLVariables();
var postData: Object = {"in": true};
request.data = JSON.stringify(postData);
request.method = URLRequestMethod.POST;
request.requestHeaders.push(header);
try {
loader.load(request);
} catch (error: Error) {
trace("Unable to load requested document.");
}
}
OUTPUT:
openHandler: [Event type="open" bubbles=false cancelable=false
eventPhase=2] progressHandler loaded:44 total: 44
EDIT 2:
function ATN() {
loader = new URLLoader();
configureListeners(loader);
var header: URLRequestHeader = new URLRequestHeader("Accept", "application/json");
var request: URLRequest = new URLRequest("https://api.thinger.io/v2/users/***");
var postData: Object = {"in": true};
request.data = JSON.stringify(postData);
request.method = URLRequestMethod.POST;
request.requestHeaders.push(header);
try {
loader.load(request);
} catch (error: Error) {
trace("Unable to load requested document.");
}
}
OUTPUT 2:
openHandler: [Event type="open" bubbles=false cancelable=false
eventPhase=2] progressHandler loaded:44 total: 44
Error opening URL 'https://api.thinger.io/v2/users/***'
httpStatusHandler: [HTTPStatusEvent type="httpStatus" bubbles=false
cancelable=false eventPhase=2 status=400 redirected=false
responseURL=null]
ioErrorHandler: [IOErrorEvent type="ioError" bubbles=false
cancelable=false eventPhase=2 text="Error #2032: Stream Error. URL:
https://api.thinger.io/v2/users/***"]

The error is in parsing the string you are providing to the URLVariables constructor. URLVariables is only really for constructing name/value pairs. If you want to send JSON simply set the data property directly:
var postData:Object = { "in": true };
request.data = JSON.stringify( postData );

Related

java angularjs spring file upload

I am trying to upload a file to a server using angularjs and Spring (to Amazon AWS).
I checked a couple of posts on uploading with the first one and the latter but I still can't get the both to work together.
File Upload using AngularJS
How to upload a file with AngularJS?
Checked also youtube for tutorials, found Black Cloud, Brent Aureli's channel and I just cannot figure it out.
You have to be authenticated in my webapp to send post requests, but I am getting errors also when I'm logged in.
Would be extremely grateful for some help.
This is my html form:
<form>
<input type="file" file-model="file">
<button ng-click="submit()" type="submit">Click</button>
</form>
Directive for the file-model:
.directive('fileModel', ['$parse', function($parse){
return {
restrict: 'A',
link: function(scope, element,attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function() {
scope.$apply(function() {
modelSetter(scope, element[0].files[0]);
})
})
}
}
}])
Controller:
.controller('UploadController', ['$scope', 'multipartForm', function($scope, multipartForm) {
$scope.file = {};
$scope.submit = function() {
var uploadUrl = '/uploadtest';
multipartForm.post(uploadUrl, $scope.file);
}
}])
Service for multipartForm:
.service('multipartForm', ['$http', function($http){
this.post = function(uploadUrl, data) {
var fd = new FormData();
for(var key in data) {
fd.append(key, data[key]);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
}
}])
Spring Endpoint:
#RestController
#RequestMapping("/storage/")
public class BucketController {
private AmazonClient amazonClient;
#Autowired
public BucketController(AmazonClient amazonClient) {
this.amazonClient = amazonClient;
}
#RequestMapping(value = "/uploadtest", method = RequestMethod.POST)
public String uploadFile(#RequestParam(value = "file") MultipartFile file) {
System.out.println("Uploading file!!!!!!!!!!!!");
return this.amazonClient.uploadFile(file);
}
}
Error that I'm getting in the browser:
angular.js:15018 Possibly unhandled rejection:
{"data":{"timestamp":1537033312586,"status":400,"error":"Bad Request","exception":"org.springframework.web.multipart.support.MissingServletRequestPartException","message":"Required request part 'file' is not present","path":"/uploadtest"},
"status":400,
"config":{"method":"POST","transformResponse":[null],
"jsonpCallbackParam":"callback",
"headers":{"Accept":"application/json,
text/plain, /",
"X-Requested-With":"XMLHttpRequest",
"Authorization":
"Basic c3p5bW9uc3R1c3pla0BnbWFpbC5jb206dGVzdA==",
"X-XSRF-TOKEN":"395d1e27-a6ee-4948-b673-39d31902e1ae"},
"url":"/uploadtest","data":{}},
"statusText":"","xhrStatus":"complete"}
The exception occurred due the missing query param 'file' which is not presented.
And in spring endpoint you should not receive a file request in Request param!
#RequestMapping(value="/uploadtest", consumes = "multipart/form-data",method = RequestMethod.POST, produces = "application/json")
public String uploadFile(MultipartHttpServletRequest request) throws Exception{
try {
MultipartFile multipartFile1 = request.getFile("file");
if (multipartFile1 != null) {
String file1 = multipartFile1.getOriginalFilename();
InputStream inputStream = multipartFile1.getInputStream();
// do whatever
}
} catch (IOException e) {
logger.error(e.getMessage());
}
return null;
}
And in Service for multipartForm change the headers content-type to : multipart/form-data
Hope this would Help!!

Not Able To Parse Web Response Content

I'm trying to retrieve JSON from a URL and read it into my application. I am having an issue when reading the WebResponse. When the response is read, it comes back as only Symbols and is not properly formatted json.
How do I get a properly formatted JSON after streaming my WebResponse?
My Javascript is as follows:
function getJsonWM() {
//var stringedData = JSON.stringify(ajaxData);
$.ajax({
type: "GET",
url: '/Default/GetQuestionByHighestScore',
//data: JSON.stringify("{}"),
contentType: "application/json; charset=utf-8",
//dataType: "json",
success: function (data) {
var label = $("#lblResults");
var json = JSON.stringify(data);
label.text(json);
//if (data.d.Pin == undefined) {
// alert("Error: " + data.d.ErrorMessage);
//} else {
// alert("Please record the following PIN: \r\n \r\n" + data.d.Pin);
//}
},
error: function (data) {
//alert("Error: " + data.d.ErrorMessage);
}
});
}
$(function() {
//$("#btnSubmit").click(getJson);
$("#btnSubmit").click(getJsonWM);
});
My controller is as follows:
public class DefaultController : Controller
{
private const string questionUrl = "https://api.stackexchange.com/2.1/questions?order=desc&sort=activity&site=stackoverflow";
public string GetQuestionByHighestScore()
{
List<Item> list = new List<Item>();
var json = GetJson(questionUrl);
var array = JsonConvert.DeserializeObject<Item>(json);
return list.OrderByDescending(x => x.Score).FirstOrDefault().ToString();
}
public string GetJson(string url)
{
var myWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
myWebRequest.Method = "GET";
myWebRequest.ContentType = "application/json";
var myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
string strResponse = String.Empty;
var encoding = Encoding.Default;
using (var reader = new StreamReader(myWebResponse.GetResponseStream(), encoding))
{
//JavaScriptSerializer js = new JavaScriptSerializer();
strResponse = reader.ReadToEnd();
}
return strResponse;
}
}
My strResponse object is as follows:
"‹\b\0\0\0\0\0\0µ\\\vÛ6¶þ+„\bÚ{G£%Q)‚ÜI“4\t6»iÓtw/”HÙšÑÕä™8Eÿû=‡”ly,y$·iÐ%òóññ¼éßi#ózñô[4|‰wÑe!›ÅÅ\"ßdMÚ¬*ÉEZ,ÿw±(ï\vY-žþ¶¨äzÓð&-‹ÅSÛv/›ZVשX<umæYžÝ¾i¶k¹x\nÝ—iÝÈJ\n`ËãX®›ëŠ7ÐÄØÅb]•IšÉë4çKì½jšuýÔ4Ó˺áñíeš/7Õe\\ææÏôêþß—7ëåóú™í°'Ëg60i½Îøöºà9’¼ÝþÄsÙÅ\"K‹Û–!ðSÜÊ;Y%Yy¯øák³²Yßn+EøûÅ\"­¯yQß«!?MxVË‹Å]*ï¯ãrS40i\a&¢:ìÞ\\,긬`|1¯›k7é]Úl¯…šªM=›:®ãBÏW¯ßd‡¡¶¤R¤Í™­Öô׬™Zih`®CŸfGSmiLµ·Æns\r؃Ï[#^ÉøVVFÝȸ1Š²1jÙMiðÂH\và\\ÄÒ(|Ô}`‘#®û{ÅòçŽ%Q,IË’ü]u'À’\0KÒ”„¤cIÊ[–¿_ìÁ˜oë_3ø’uY7ËJê\ažó/eaÀÞÔ«4iF‘é[¬‡L'p=Ë\n§\"3\bÆ‘y¹¬øo¸¦þhºŒ\a¡—D‚òÀŠBG¸’{^苘E2òe\v[ñ,²hÒ¸,žTÏ>üð$Âñ\aÞ4+m–“ÜÎÐ\\ï(§ ù!­©#v¼a ·MG`\rÄsÁŠ4fšÃFÜIc\rÝÊ*ï#\bs4 wµ565b¸*ïb“G\0„=*ßjZÒ£E´-Q´DÑ ½niûð[o›•’$u\t(nêq!Ø—¥>sN!m\fXÙÊ¿\\–å2“H\nøh\0'jYŒ¼æÅ««7âê­yµû¯÷ùÅ'35~i^_Õ/£[s½*›RËÊ/ˆºc€}¿ªÒšü$y6aíÌÌIá\0鈹gcÌG0qTXj²caÉ|¶°“g°oŒ0\b²PcÁÐÒÂÈ%#DôwµïbN÷¾Ô½¿ù–´ýû(«6ÑÖ#ÆÓ¬NøŒ˜“YkœÀºjÇ¥\\yãû¨f#oL¤IGDÂñ¤ð…å$qB=ϱœ€ZüBo–H“U&\vqS®øtíÜNÉìÓNÀ.˜‚¶ÏÂœZvh\ràÊòèl¹†4æýŠ7µc9¨7C&I§°ŠÆ=ß* É\fÕ0Gí,61ô­7ÑþB½è^ö0øà"
Looks like the server returns gzip encoded response. So make sure that you have set the AutomaticDecompression property when making your HTTP request:
public string GetJson(string url)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
using (var response = (HttpWebResponse)request.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
string strResponse = reader.ReadToEnd();
return strResponse;
}
}
Also please get rid of those application/json content types. You are making a GET request which doesn't have a body - you are not sending any JSON. Also get rid of the contentType switch in your jQuery AJAX request (same reason).

Obtaining JSON data from server into $.ajax call

I have a problem with JSON and JQUERY. In my web application I submit some data (through an $.ajax call) to a servlet and want to receive back some informations from this servlet once it has done.
I'm using JSONObject in this way:
function check(){
$.ajax({
url: "/check",
type: "POST",
dataType: "json",
success: on_check_ok,
error: function(){
alert("something wrong happened");
},
data: {
players_code: $("#players_code").val(),
},
});
return false;
}
function on_check_ok(data) {
var json = data;
$("#display").text(json.check); //"display" is a <div> into index.html
};
and this is doPost() method in my servlet code:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
String code_array = request.getParameter("players_code");
System.out.println("Player's code is: " + code_array);
int arr = Integer.parseInt(code_array);
LinkedList<Integer> stack = new LinkedList<Integer>();
while(arr > 0){
stack.push(arr%10);
arr = arr/10;
}
int index = 0;
while(!stack.isEmpty()){
array[index] = (int)stack.pop();
index++;
}
mm.checkGuess(array);
response.getWriter().write(mm.ris + " ");
tries++;
System.out.println("TRIES: " + tries);
JSONObject obj = new JSONObject();
obj.put("check", tries);
String json = obj.toString();
out.write(json);
System.out.println("JSON " + json);
}
}
but cannot get displayed any information. Seems that JSONObject has been created correctly, since I can display it on console. I'm having hard times on getting this data back to javascripts.
That's my code, what I'm doing wrong? Or, is there an alternative way to get the same result? thanks for the help!

Code error in NetConnection.call method

I am new to ActionScript 3. I am attempting to call the server from the client using the nc.call() method to see if this was a good option to use for clients to communicate back and forth in a chat application.
I received a compile error message:
1118: Implicit coercion of a value with static type Object to a possibly unrelated type flash.net:Responder.
Can somebody please help me fix this error?
This is my client-side code below:
import flash.net.NetConnection;
import flash.events.NetStatusEvent;
var nc:NetConnection = new NetConnection();
nc.connect("rtmfp:/fms/textchatexample");
nc.addEventListener(NetStatusEvent.NET_STATUS, netHandler);
function netHandler(event:NetStatusEvent):void {
switch(event.info.code) {
case "NetConnection.Connect.Success":
trace("Your Connected UP");
break;
}
}
var test:Object = new Object();
test.onResult = function(arg) {
trace(arg);
};
nc.call("sendMsg", test, "just, a test call"); ERROR LINE
try to replace your Object instance with a Responder:
var test:Responder = new Responder(
function(result):void
{
trace('ok :', result);
},
function(status):void
{
trace('status :', status);
});
instead of your Object

How to return exception data in json format from App_Error in global.asax?

I'm working on Asp.net MVC project as a single page application for error handling. I want to return json data from Application_Error method in global.asax to UI and show it by jQuery or call a controller and return partialView.
I don't want to refresh the page or redirect it to Error page.
here is the way to go
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
// if the error is NOT http error, then stop handling it.
if (!(exception is HttpException httpException))
return;
if (new HttpRequestWrapper(Request).IsAjaxRequest())
{
Response.Clear();
Response.TrySkipIisCustomErrors = true;
Server.ClearError();
Response.ContentType = "application/json";
Response.StatusCode = 400;
JsonResult json = new JsonResult
{
Data = exception.Message
};
json.ExecuteResult(new ControllerContext(Request.RequestContext, new BaseController()));
}
}
//Write This code into your global.asax file
protected void Application_Error(Object sender, EventArgs e)
{
var ex = Server.GetLastError();
//We check if we have an AJAX request and return JSON in this case
if (IsAjaxRequest())
{
Response.Write(JsonConvert.SerializeObject(new
{
error = true,
message = "Exception: " + ex.Message
})
);
}
}
private bool IsAjaxRequest()
{
//The easy way
bool isAjaxRequest = (Request["X-Requested-With"] == "XMLHttpRequest")
|| ((Request.Headers != null)
&& (Request.Headers["X-Requested-With"] == "XMLHttpRequest"));
//If we are not sure that we have an AJAX request or that we have to return JSON
//we fall back to Reflection
if (!isAjaxRequest)
{
try
{
//The controller and action
string controllerName = Request.RequestContext.
RouteData.Values["controller"].ToString();
string actionName = Request.RequestContext.
RouteData.Values["action"].ToString();
//We create a controller instance
DefaultControllerFactory controllerFactory = new DefaultControllerFactory();
Controller controller = controllerFactory.CreateController(
Request.RequestContext, controllerName) as Controller;
//We get the controller actions
ReflectedControllerDescriptor controllerDescriptor =
new ReflectedControllerDescriptor(controller.GetType());
ActionDescriptor[] controllerActions =
controllerDescriptor.GetCanonicalActions();
//We search for our action
foreach (ReflectedActionDescriptor actionDescriptor in controllerActions)
{
if (actionDescriptor.ActionName.ToUpper().Equals(actionName.ToUpper()))
{
//If the action returns JsonResult then we have an AJAX request
if (actionDescriptor.MethodInfo.ReturnType
.Equals(typeof(JsonResult)))
return true;
}
}
}
catch
{
}
}
return isAjaxRequest;
}
//Write this code in your ajax function in html file
<script type="text/javascript">
$.ajax({
url: Url
type: 'POST',
data: JSON.stringify(json_data),
dataType: 'json',
cache: false,
contentType: 'application/json',
success: function (data) { Successfunction(data); },
error: function (xhr, ajaxOptions, thrownError) {
var obj = JSON.parse(xhr.responseText);
if (obj.error) {
show_errorMsg(obj.message);
}
}
});
</script>