Upload arbitrary data in HTTP Post in Flex

2019-05-21 14:58发布

We currently have a Java applet that generates a lot of data and uploads it to our servers. One of the upload methods we have is to use an HTTP POST to our server, the contents of which are just the raw data (no multipart encoding or anything).

I'm looking at implementing a Flex app that does the same thing, but I don't see a way to duplicate that network behavior. All the HTTP-related network classes in Flex seem to work under the assumption that you're simply making a request. I don't see a way to actually set the payload of the POST (other than setting a couple query parameters, which wouldn't work here).

What I'd really like is to be able to initiate an HTTP POST, but then be able to write to the connection like I would a socket. Is this possible without having to write my own HTTP implementation on top of the Socket class? Is there any way to set the payload of an HTTP POST within Flex?

Clarification: Being able to create a data buffer and send that to the server is sufficient (which it looks like is possible). It would be better if I could treat the connection as a socket and send data to it over time, instead of all at once, but that isn't strictly required.

1条回答
Fickle 薄情
2楼-- · 2019-05-21 15:21

It sounds like you're sort of asking two questions. Yes, there is a way to set the payload of an HTTP POST within Flex, and to upload files of any format to your server:

private function doPost():void
{
    var yourData:ByteArray = new ByteArray();
    var encoder:Base64Encoder = new Base64Encoder();

    for (var i:int = 0; i < 10000; i++)
        yourData.writeByte(i);

    yourData.position = 0;
    encoder.encodeBytes(yourData);

    var req:URLRequest = new URLRequest("http://yourdomain.com/yourservice.ext");
    req.method = URLRequestMethod.POST;

    var postData:URLVariables = new URLVariables();
    postData.userData = encoder.flush();

    req.data = postData;

    var loader:URLLoader = new URLLoader();
    loader.dataFormat = URLLoaderDataFormat.BINARY;
    loader.addEventListener(Event.COMPLETE, loader_complete);
    loader.load(req);
}

private function loader_complete(event:Event):void
{
    trace("Upload complete!");
}

... but it also sounds like you want to connect, keep the connection open and then write to it arbitrarily "like a socket"; if that's the case, then other than using the Socket classes for that purpose, I don't believe there's a built-in mechanism, no. Hope it helps nonetheless!

查看更多
登录 后发表回答