Http post xml html

Javascript xml http post with body

Is there any way to perform a chunked upload using javascript, opening a connection but only uploading blobs of data bit by bit? HTTP chunked data transfer encoding is not technically necessary for sending data a few chunks at a time, I believe regular HTTP data transfer also only sends data a few chunks at a time but the «chunking» is done at the TCP level instead (please correct me if I’m wrong here).

How To Post XML via JavaScript to REST API?

I’m trying to POST XML via JavaScript to a REST API.

The Request Data looks like this:

How do I define the postString above if my code looks like this below:

xhr.open('POST',URLgameUpdateAction); xhr.setRequestHeader('Content-type','application/x-www.form-urlencoded'); xhr.send(**postString**); 

You can pass the XML as a simple string.

xhr.open('POST',URLgameUpdateAction); xhr.setRequestHeader('Content-type','application/x-www.form-urlencoded'); xhr.send("\ \ \ 2\ 2621440\ \ "); 

How can I send XML data through a POST request in, I don’t know if it’s even possible or not but here’s what I have so far (the XML data is in the body of a html file in html format): var http = new XMLHttpRequest (); var url = » (Server data upload service url)»; var params = encodeURIComponent (window.getElementsByTagName («body») [0].innerHTML); http.open («POST», url, true); http

XmlHttpRequest with chunked request body?

I know how to handle chunked downloads in javascript, using the XmlHttpRequest object. Is there any way to perform a chunked upload using javascript, opening a connection but only uploading blobs of data bit by bit?

Читайте также:  Создать временный файл на php

I know chunked uploads should be possible with Http 1.1 servers, and have found a lot of references to making chunked uploads using various other platforms (C# java etc.) but have not found any references to doing so in the browser with javascript.

EDIT: The use case is to stream data up to the server, and not to upload a large file, kind of mirroring the use of a chunked response to stream data down to the client. This is as an alternative to making individual ajax requests, since the chunks of data that’s going up from client to server are pretty frequent (< 0.5s interval).

As of today (November 2021), I believe support for UPLOADS using HTTP chunked data transfer is still largely missing in browsers.

If you look at the «Send ReadableStream in request body» column of the browser support matrix for the Request (Fetch API), you can see that it is currently «No» for all browsers except «Deno». You will however notice the «Experimental» flag beside the column. So it is available experimentally in some browsers such as Chrome. I wouldn’t hold your breath about it becoming mainstream anytime soon though.

HTTP chunked data transfer encoding is not technically necessary for sending data a few chunks at a time, I believe regular HTTP data transfer also only sends data a few chunks at a time but the «chunking» is done at the TCP level instead (please correct me if I’m wrong here). Consequently, both protocols can be used to stream a file upload. WebSockets are of course another option as well. The main difference in which protocol to choose is based on whether or not you know the final length of the stream in advance or not.

If you need to stream upload data for which you DON’T know the length in advance (such as live video, video conference calls, remote desktop sessions, chats, etc.) then your best bet is perhaps the WebSocket API (or something built on top of it).

If you need to stream upload data for which you DO know the length in advance (files, images, videos, etc.) then I believe your best bet is probably a normal POST or PUT using the Fetch API or even the old XmlHttpRequest API.

You can use the FileReader API and the slice method.

with slice you can get block of data that you can upload, then you need to reassemble them server side.

here is a good intro on how to handle files in javascript http://www.html5rocks.com/en/tutorials/file/dndfiles/

you can have a look at http://caniuse.com/#feat=filereader for browser support

Javascript — Send POST data using XMLHttpRequest, The answer that has few votes but got marked correct uses two extra headers: http.setRequestHeader(«Content-length», params.length); and http.setRequestHeader(«Connection», «close»);.Are they needed? Are they perhaps only needed on certain browsers? Code samplevar http = new XMLHttpRequest();var url = ‘get_data.php’;var params = ‘orem=ipsum&name=binny’;http.open(‘POST’, url, true);http.setRequestHeader(‘Content-type’, ‘application/x-www-form-urlencoded’);Feedback

How do I POST a XML body in Angular 5?

I’m currently working on an Ionic application that is supposed to make REST API calls with XML as the body. I’m having trouble getting the call to actually post with XML. This is my LoginProvider. I’m using DOMParser to parse my data to XML before posting it to the API.

import < HttpClient, HttpHeaders>from '@angular/common/http'; import < Injectable >from '@angular/core'; import * as Constants from '../../services/constants'; @Injectable() export class LoginProvider < constructor(public http: HttpClient) < >postLogin(username : String, password : String) < let parser = new DOMParser(); let xmlString = "" + username + " " + password + " "; let doc = parser.parseFromString(xmlString, "application/xml"); console.log(doc); let headers = new HttpHeaders() .set('Access-Control-Allow-Origin', '*') .set('Content-Type', 'application/xml'); return new Promise(resolve => < this.http.post(Constants.API_ENDPOINT + "/authentication-point/alm-authenticate", doc, ).subscribe(data => < resolve(data); >, err => < console.log(err); >); >); > > 

But when i inspect the post request in Google Chrome i get the following:

The request payload seems to be in JSON instead of XML. How can i make it actually send the XML file?

I have already tried changing the body to a xml string instead of the file, and changing the content type but this still gave the same error.

I’m using Ionic-angular version 3.9.2 with angular version 5.0.3

let doc = parser.parseFromString(xmlString, "application/xml"); 

doc is an object representing the DOM of an XML document.

http.post(Constants.API_ENDPOINT + "/authentication-point/alm-authenticate", doc, ) 

You are passing doc as an argument to http.post .

Since you are passing an object, Angular is trying to convert it to JSON.

If you are encoding the request payload yourself (i.e. you don’t want Angular to convert it to JSON) then you need to pass a string .

Pass xmlString instead of doc .

Javascript — How to Send a body of data to, Then send it using POST like : var xhr = new XMLHttpRequest (); xhr.open (method, url); xhr.setRequestHeader (‘Authorization’, ‘Bearer ‘ + access_token); xhr.onload = requestComplete; xhr.send (params); I know Im going to encounter errors because there’s a proper way of formatting my «request body». It looks like a mixture of …

Angular $http.post not returning XML

I am trying to call a web service with angular, but not having much luck. The service takes a POST request with no POST body, and returns XML. I can confirm that the service works with a raw XMLHttpRequest call:

var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() < if(xhr.readyState == 4) console.log(xhr.responseText); // Returns data >xhr.open("POST", "https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML", true); xhr.send(null); 
$.ajax(< url: 'https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML', type: "POST", success: function(data)< console.log(data); // Returns data >, error: function (hxr, status, errorThrown) < console.log(status); >>); 

However, I’m not getting anything back when I try it with angular’s $http service:

angular.module('TestApp',[]) .controller('TestController', function($scope, $http)< $http(< method: "POST", url: 'https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML' >).success(function(data, status, headers, config)< console.log("data:"); console.log(data); // Returns null >).error(function(data, status, headers, config)< console.log("error status:"); console.log(status); // No errors returned >) >) 
angular.module('TestApp',[]) .controller('TestController', function($scope, $http)< $http.post( 'https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML' ).success(function(data, status, headers, config)< console.log("data:"); console.log(data); >).error(function(data, status, headers, config)< console.log("error status:"); console.log(status); >) >) 

Note that the $http.post shortcut method has a second data parameter, but I have no data to pass. If I include the parameter as null, Chrome says:

Since the $http.post shortcut method does not complain about missing out the data parameter, I have deliberately missed it out.

I need to be able to make the POST call with no data, as is possible with a raw XMLHttpRequest call, or jQuery’s ajax method. What might be going wrong? Thanks!

(NB, the API is public, so don’t worry about the API key I’ve posted. It’s a valid API key, which I’ll keep active only while this question is open)

Angular by default expecting to get JSON from your server you can change that by adding

var app = angular.module('app', []);app.controller('homeCtrl', function($scope, $http) < $scope.xml = ""; $http(< method: "POST", url: 'https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML', headers: < "Accept": "application/xml" >>).success(function(data, status, headers, config) < console.log("data:"); console.log(data); // Returns null $scope.xml = data; >).error(function(data, status, headers, config) < console.log("error status:"); console.log(status); // No errors returned >)>);

Send a GET request with a body in JavaScript, No, it is not possible to send a GET request with a body in JavaScript. it looks like the payload is simply not sent. That is correct. This is defined in the specification: The send (body) method must run these steps: If the request method is GET or HEAD, set body to null. Also a request via the Fetch …

Источник

Как сделать post запрос xml?

Следует выполнить POST запрос на добавление нового подписчика из xml и вывести результат (ответное xml).
Как это реализовать? curl?
Прочитал темы по сабжу, но, видимо, не все понял. можно на моем примере пояснить?

POST не может быть безымянным, должно быть поле в котором будут переданы данные, в вашем случае это xml. Не совсем понятна суть, вам надо решить вопрос с какой стороны сервера или клиента апи?

т.е. у меня на сайте стоит форма. в ней поля — Имя, Email и checkbox получать рассылку или нет
если стоит галочка получать рассылку, то в mysite.com/api/
нужно послать xml запрос методом post с текстом (указанным выше)

$ch = curl_init(); $data = array('request' => $xml); curl_setopt($ch, CURLOPT_URL, "http://mysite.com/api/"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $response=curl_exec($ch); curl_close($ch); print_r($response); 
$data = array('request' => $xml,'Content-Type: text/xml; charset=utf-8'); 
$ch = curl_init(); $data = array('Content-Type: text/xml; charset=utf-8'); curl_setopt($ch, CURLOPT_URL, "http://mysite.com/api/api?"+$xml); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $response=curl_exec($ch); curl_close($ch); print_r($response); 
 xxxx AddAndUpdate false 1 aa@aa.aa name  '; $ch = curl_init(); $data = array('Content-Type: text/xml; charset=utf-8'); curl_setopt($ch, CURLOPT_URL, "https://mysite.com/api?"+$xml); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $response=curl_exec($ch); curl_close($ch); print_r($response); ?>

однако, есть пример на c# (asp), реализующий то же самое. Он рабочий.

WebRequest request = WebRequest.Create("https://mysite.com/api"); request.Method = "POST"; string postData = @" xxxx AddAndUpdate false 1 aa@aa.aa name  "; byte[] byteArray = Encoding.UTF8.GetBytes(postData); request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); try < WebResponse response = request.GetResponse(); >catch (WebException ex) < // using (Stream data = ex.Response.GetResponseStream()) // < // string text = new StreamReader(data).ReadToEnd(); // Response.Write("

" + text); // > >

и почему-то в мануале написано про контент тайп text/xml, а в примере application/x-www-form-urlencoded

MrBlack, curl_setopt($ch, CURLOPT_POSTFIELDS, $data); замените на curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); , и добавьте curl_setopt($ch, CURLOPT_HTTPHEADER, array($xml);

Источник

Оцените статью