Im trying to make a simple HTTP URLReqest in Adobe Flex, heres the code roughly:
var requestSender:URLLoader = new URLLoader();
var urlRequest :URLRequest = new URLRequest("http://localhost:8888");
var msg:String = "data=blah";
urlRequest.data = msg;
urlRequest.contentType = "application/x-www-form-urlencoded";
urlRequest.method = URLRequestMethod.POST;
This produces something close to:
POST / HTTP/1.1
Referer: app:/PersonSearch.swf
Accept: text/xml, application/xml, application/xhtml+xml, ...
x-flash-version: 10,1,85,3
Content-Type: application/x-www-form-urlencoded
Content-Length: 102
Accept-Encoding: gzip,deflate
User-Agent: Mozilla/5.0 (Windows; U; en-US) ...
Host: 127.0.0.1:8888
Connection: Keep-Alive
data=blah
What I really want is:
POST / HTTP/1.1
Content-Type:application/x-www-form-urlencoded
Connection:close
Via:MDS_777
Accept:*/ *
Host:localhost:8888
Content-Length:104
data=blah
Anyone know how I remove the fields like Accept-Encoding, add fields like "Via" and set Connection to "close"?
Also how do we get the responce from the HTTP request?
Thanks
Phil
The Flash Player doesn't allow you to change the Accept-Encoding or Via headers through ActionScript. If you try do that you will get a message like this one:
Error #2096: The HTTP request header
Accept-Encoding cannot be set via
ActionScript.
If you are using URL variables you can try to simplify your code by doing this:
var variables:URLVariables = new URLVariables();
variables.data = "blah"; //same as doing data=blah
variables.data2 = "blah2"; //same as doing data2=blah2
var requestSender:URLLoader = new URLLoader();
var urlRequest:URLRequest = new URLRequest("http://localhost:8888");
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = variables;
To get the response you will have to listen for the Event.COMPLETE on the "requestSender":
requestSender.addEventListener(Event.COMPLETE, completeHandler);
private function completeHandler(event:Event):void {
// do something with requestSender.data (or URLLoader(event.target).data)
}
Related
This code:
using (var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(10) })
{
using (var content = new MultipartFormDataContent())
{
content.Add(new StringContent("abc"), "token");
var response = await client.PostAsync("http://localhost", content);
var result = await response.Content.ReadAsStringAsync();
}
}
Generates the following HTTP request:
POST http://localhost/ HTTP/1.1
Host: localhost
Content-Type: multipart/form-data; boundary="4b39ed14-752b-480a-9846-fc0019132d15"
Content-Length: 174
--4b39ed14-752b-480a-9846-fc0019132d15
Content-Type: text/plain; charset=utf-8
Content-Disposition: form-data; name=token
abc
--4b39ed14-752b-480a-9846-fc0019132d15--
We have a client who says their WAF is blocking the request because the name parameter should be quoted
Content-Disposition: form-data; name="token"
I have seen some differences in opinion on this:
https://github.com/akka/akka/issues/18788
https://github.com/akka/akka-http/issues/386
Does anyone know what is correct here?
I posted this to https://github.com/dotnet/runtime/issues/72447
Either form is correct, apparently
Please help to advise for my issue below.
I try to create an enrollment using sample code from here
private async Task<HttpResponseMessage> MakeRequest()
{
string path = #"<path_to_wav_file>";
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "<my_key>");
// Request parameters
queryString["shortAudio"] = "true";
queryString["identificationProfileId"] = "<my_profile_id>";
var uri = "https://westus.api.cognitive.microsoft.com/spid/v1.0/identificationProfiles/<my_profile_id>/enroll?" + queryString;
HttpResponseMessage response;
// Request body
byte[] byteData = File.ReadAllBytes(path);
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response = await client.PostAsync(uri, content);
}
return response;
}
and got the response
{StatusCode: 202, ReasonPhrase: 'Accepted', Version: 1.1, Content:
System.Net.Http.StreamContent, Headers: { Pragma: no-cache
Operation-Location:
https://westus.api.cognitive.microsoft.com/spid/v1.0/operations/af54c843-8df9-4511-8d65-4825ebec024d
apim-request-id: 37567cff-d259-4a1d-82fc-9fc884edcfe3
Strict-Transport-Security: max-age=31536000; includeSubDomains;
preload x-content-type-options: nosniff Cache-Control: no-cache
Date: Tue, 08 Jan 2019 07:12:05 GMT X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET Content-Length: 0 Expires: -1 }}
said that
{"error":{"code":"Unspecified","message":"Access denied due to invalid
subscription key. Make sure you are subscribed to an API you are
trying to call and provide the right key."}}
The error message is strange because I used the same Subscription Key that created profile successfully.
I think you should use ("Ocp-Apim-Subscription-Key", "") when make request to
https://api.projectoxford.ai/spid/v1.0/operations/af54c843-8df9-4511-8d65-4825ebec024d
I'm writing a GWT frontend for a personal project, and I'm having problems with some HTTP requests. When I do a CORS POST request, it works fine
String url = BASE_URL + "students/";
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
builder.setHeader("Content-Type", "application/vnd.onelostlogician.student+json");
builder.setHeader("Accept", "application/json");
StringBuilder basicAuth = new StringBuilder();
basicAuth.append(username.getValue());
basicAuth.append(":");
basicAuth.append(password.getValue());
String basicAuthStr = basicAuth.toString();
builder.setHeader("Lambda-Authorization", "Basic " + toBase64(basicAuthStr.getBytes()));
StudentWriter studentWriter = GWT.create(StudentWriter.class);
try {
builder.sendRequest(studentWriter.write(student), new RequestCallback() {
public void onError(Request request, Throwable exception) {
addItemDialog.close();
responseDialog.open();
loadingIcon.setVisible(false);
responseHeading.setText("No response");
responseLabel.setText(request.toString());
}
public void onResponseReceived(Request request, Response response) {
loadingIcon.setVisible(false);
String responseText = response.getText();
List<Map.Entry<Integer, Student>> students = model.getList();
Integer studentId = Integer.parseInt(responseText);
students.add(new AbstractMap.SimpleEntry<>(studentId, student));
model.setList(students);
// clear text fields
className.setValue("");
additionLevel.setValue("");
additionProblems.setValue("");
subtractionLevel.setValue("");
subtractionProblems.setValue("");
multiplicationLevel.setValue("");
multiplicationProblems.setValue("");
divisionLevel.setValue("");
divisionProblems.setValue("");
addItemDialog.close();
}
});
} catch (RequestException _) {
// Code omitted for clarity
}
The options request gets a 200 response (chrome network inspection below):
General
Request URL:https://[redacted].execute-api.eu-west-1.amazonaws.com/v1/students/
Request Method:OPTIONS
Status Code:200
Remote Address:54.230.9.41:443
Referrer Policy:no-referrer-when-downgrade
Response Headers
access-control-allow-headers:content-type, lambda-authorization
access-control-allow-methods:post, get, put
access-control-allow-origin:*
content-length:0
content-type:application/json
date:Wed, 13 Sep 2017 14:56:32 GMT
status:200
via:1.1 5db82aafd9021b07695423274288b59e.cloudfront.net (CloudFront)
x-amz-cf-id:8nJ2gzqHFPiiDOOeEelzkpI7Ga9SFdEcljiLt2pvm7Z995_GicxPVw==
x-amzn-requestid:bb0e23db-9893-11e7-bbbe-9bea7d9d70bf
x-amzn-trace-id:sampled=0;root=1-59b94720-d892209d8c5c2a04832bdb85
x-cache:Miss from cloudfront
Request Headers
:authority:[redacted].execute-api.eu-west-1.amazonaws.com
:method:OPTIONS
:path:/v1/students/
:scheme:https
accept:*/*
accept-encoding:gzip, deflate, br
accept-language:en-GB,en-US;q=0.8,en;q=0.6
access-control-request-headers:content-type,lambda-authorization
access-control-request-method:POST
origin:http://127.0.0.1:8888
referer:http://127.0.0.1:8888/ArithmeticExerciseGeneratorClient.html
user-agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36
and then the POST request occurs as expected
General
Request URL:https://[redacted].execute-api.eu-west-1.amazonaws.com/v1/students/
Request Method:POST
Status Code:201
Remote Address:54.230.9.41:443
Referrer Policy:no-referrer-when-downgrade
Response Headers
access-control-allow-origin:*
content-length:1
content-type:application/json
date:Wed, 13 Sep 2017 14:56:33 GMT
status:201
via:1.1 5db82aafd9021b07695423274288b59e.cloudfront.net (CloudFront)
x-amz-cf-id:gxYrwctM75ObiPyS4nD69jXSO4dBaMAOZmXXX0mPE4wMgCdcjUSQsA==
x-amzn-requestid:bb381a33-9893-11e7-a1f1-17fd67ca388c
x-amzn-trace-id:sampled=0;root=1-59b94720-1c1e3a8d8c9ce2741c789241
x-cache:Miss from cloudfront
Request Headers
:authority:[redacted].execute-api.eu-west-1.amazonaws.com
:method:POST
:path:/v1/students/
:scheme:https
accept:application/json
accept-encoding:gzip, deflate, br
accept-language:en-GB,en-US;q=0.8,en;q=0.6
content-length:224
content-type:application/vnd.onelostlogician.student+json
lambda-authorization:Basic [redacted]
origin:http://127.0.0.1:8888
referer:http://127.0.0.1:8888/ArithmeticExerciseGeneratorClient.html
user-agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36
Request Payload
{"className":"6T","additionProblemId":4,"additionNoOfProblems":5,"subtractionProblemId":3,"subtractionNoOfProblems":5,"multiplicationProblemId":2,"multiplicationNoOfProblems":5,"divisionProblemId":1,"divisionNoOfProblems":5}
Unfortunately, a PUT request to a very similar resource, on the same server, doesn't. The code is almost identical:
String url = BASE_URL + "students/" + studentId;
RequestBuilder builder = new RequestBuilder(RequestBuilder.PUT, url);
builder.setHeader("Content-Type", "application/vnd.onelostlogician.student+json");
builder.setHeader("Accept", "application/json");
StringBuilder basicAuth = new StringBuilder();
basicAuth.append(username.getValue());
basicAuth.append(":");
basicAuth.append(password.getValue());
String basicAuthStr = basicAuth.toString();
builder.setHeader("Lambda-Authorization", "Basic " + toBase64(basicAuthStr.getBytes()));
StudentWriter studentWriter = GWT.create(StudentWriter.class);
try {
builder.sendRequest(studentWriter.write(student), new RequestCallback() {
public void onError(Request request, Throwable exception) {
addItemDialog.close();
responseDialog.open();
loadingIcon.setVisible(false);
responseHeading.setText("No response");
responseLabel.setText(request.toString());
}
public void onResponseReceived(Request request, Response response) {
loadingIcon.setVisible(false);
responseDialog.open();
loadingIcon.setVisible(false);
responseHeading.setText("Response: " + response.getStatusCode());
responseLabel.setText(response.getText());
}
});
} catch (RequestException _) {
// Code omitted for clarity
}
The options request gets a 200 response:
General
Request URL:https://[redacted].execute-api.eu-west-1.amazonaws.com/v1/students/4
Request Method:OPTIONS
Status Code:200
Remote Address:54.230.9.41:443
Referrer Policy:no-referrer-when-downgrade
Response Headers
access-control-allow-headers:content-type, lambda-authorization
access-control-allow-methods:get, put
access-control-allow-origin:*
content-length:0
content-type:application/json
date:Wed, 13 Sep 2017 14:58:38 GMT
status:200
via:1.1 5db82aafd9021b07695423274288b59e.cloudfront.net (CloudFront)
x-amz-cf-id:0PoyOa6oDBSmU7iCWZyeSZFqWxZvumN8C4GtHn8rsoJK5AURbj3kxQ==
x-amzn-requestid:063270d4-9894-11e7-9d66-71b07b2689ef
x-amzn-trace-id:sampled=0;root=1-59b9479e-39be94b25784b92027fa2753
x-cache:Miss from cloudfront
Request Headers
:authority:[redacted].execute-api.eu-west-1.amazonaws.com
:method:OPTIONS
:path:/v1/students/4
:scheme:https
accept:*/*
accept-encoding:gzip, deflate, br
accept-language:en-GB,en-US;q=0.8,en;q=0.6
access-control-request-headers:content-type,lambda-authorization
access-control-request-method:PUT
origin:http://127.0.0.1:8888
referer:http://127.0.0.1:8888/ArithmeticExerciseGeneratorClient.html
user-agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36
…but after receiving a successful OPTIONS response, it does not make the PUT request at all.
In the Chrome console I get:
XMLHTTPRequest cannot load https://[redacted]/v1/students/5. Method
PUT is not allowed by Access-Control-Allow-Methods in preflight
response
I don't understand that error, given that we can see "put" in the access-control-allow-methods response header for the preflight OPTIONS request shown above.
Any ideas what I'm doing wrong?
In the POST response, the allowed methods header is
access-control-allow-methods:post, get, put
In the PUT response, the allowed methods header is
access-control-allow-methods:get, put
Note that the required method is the first in the list of the POST case, but second in the list in the PUT case. When I modified the server to put the method under consideration first in the list (and, also, to make it case sensitive, because HTTP method names are case sensitive), the browser then performed the required followup PUT request.
I have to stream an ip camera inside a web application. Typically I do this by adding the url to an img tag. The problem this time is that the request requires digest authentication. Because of this, I want to create a proxy method to handle the authentication and stream out the data back to the client. I am currently trying to do this with an HttpHandler.
using System;
using System.Net;
using System.Web;
public class HelloWorldHandler : IHttpHandler
{
#region IHttpHandler Members
private const int BUFFERSIZE = 1048576;
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
HttpWebRequest webRequest = null;
#region Prepare the request object
webRequest = (HttpWebRequest)WebRequest.Create("http://url/cgi/image.php?type=live");
webRequest.Method = "GET";
webRequest.ContentType = "multipart/x-mixed-replace; boundary=------MJPEG FAME--------";
webRequest.Credentials = new NetworkCredential(username, password);
#endregion Prepare the request object
#region Cycle through and return output
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
// GETS STUCK HEAR FOR OBVIOUS REASONS. NOT SURE HOW TO BUFFER A CHUNK, STREAM THE CHUNK AND REPEAT
System.IO.Stream fileStream = webResponse.GetResponseStream();
Byte[] buffer = new byte[1048576];
int bytesRead = 1;
context.Response.ContentType = "image/png";
while (bytesRead > 0)
{
bytesRead = fileStream.Read(buffer, 0, BUFFERSIZE);
if (bytesRead == BUFFERSIZE)
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
else if (bytesRead > 0)
{
byte[] endBuffer = new byte[bytesRead];
Array.Copy(buffer, endBuffer, bytesRead);
context.Response.OutputStream.Write(endBuffer, 0, endBuffer.Length);
}
}
fileStream.Dispose();
webResponse.Close();
#endregion Cycle through and return output
}
#endregion
}
If you look at my comments in the code, I have marked the obvious place where the code is failing. When I am getting the response stream, it will never end until an memory exception is thrown. This seems obvious enough but I am not sure how to actually handle the buffer issue. I think I need to be able to buffer a chunk, stream it, buffer anther and repeat.
For reference this an example of the headers when I make a direct connection through a browser.
REQUEST
GET http://url/cgi/image.php?type=live HTTP/1.1
Host: url
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Authorization: Digest something something something
RESPONSE
HTTP/1.1 200 OK
X-Powered-By: PHP/5.3.10-1ubuntu3.8
Content-type: multipart/x-mixed-replace; boundary=------MJPEG FAME--------
Transfer-Encoding: chunked
Date: Mon, 04 Nov 2013 23:39:22 GMT
Server: lighttpd/1.4.28
Any advice would be greatly appreciated.
Thanks,
Chad
As #Aristos mentioned, the key was to set the context.Repsonse.Flush(). Though this part of the problem has been solved, I am now presented with another problem.
I have opened up another thread specific to that problem. https://stackoverflow.com/questions/19849148/is-it-possible-to-close-an-httpcontext-object-that-is-inside-an-httphandler-from
Thanks,
Chad
I am working on Ubuntu 12.04. This is my simple code for implementing HTTP GET method using URLConnection.
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class HttpURLConnectionExample {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
HttpURLConnectionExample http = new HttpURLConnectionExample();
System.out.println("Testing 1 - Send Http GET request");
http.sendGet();
}
// HTTP GET request
private void sendGet() throws Exception {
String url = "https://www.google.com/search?q=flower";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
}
But when i compile and run this code from ubuntu terminal, the output of this code does not give the content of the page specified by the URL. Rather it gives the following output
Testing 1 - Send Http GET request
Sending 'GET' request to URL : http://www.google.com/search?q=flower
Response Code : 307
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>307 Temporary Redirect</title></head><body><h1>Temporary Redirect</h1><p>The document has moved here.</p><hr><address>Apache/2.2.22 (Fedora) Server at www.google.com Port 80</address></body></html>
This issue holds for any URL I specify in the code. Moreover, I tried to access web content using telnet client like
telnet www.google.com 80
GET /
and it gives the similar result not only for www.google.com but for every URL.
I am a student at IIT Bombay and may be it has something to do with https://ifwb.iitb.ac.in.
I also want to stick to java.net and not apache httpclient. So help me out of this.
It seems you're rejected by the server due incomplete request. It's a good idea to use any sniffer like Fiddler or Wireshark to "learn by example": compare your requests and requests from particular software like browsers.
Below is an excerpt from Wireshark dump, how IE10 sends GET request to interested URL. As you can see, there are various fields that describe capabilities and expectations of your client side so queried server can return the answer in most suitable and consumable form. Consult with Google/RFC to see the meaning of each parameter passed in:
GET /search?q=flower HTTP/1.1
Accept: text/html, application/xhtml+xml, /
Accept-Language: en-US
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64;
Trident/6.0)
Accept-Encoding: gzip, deflate
Host: www.google.com
DNT: 1
Connection: Keep-Alive
Cookie: [some private info here]