GithubHelp home page GithubHelp logo

dart-lang / http Goto Github PK

View Code? Open in Web Editor NEW
1.0K 57.0 341.0 2.68 MB

A composable API for making HTTP requests in Dart.

Home Page: https://pub.dev/packages/http

License: BSD 3-Clause "New" or "Revised" License

Dart 91.56% Ruby 0.49% Swift 0.27% Objective-C 2.77% C 0.14% Kotlin 0.64% CMake 1.77% C++ 2.18% HTML 0.18%
dart flutter http http-client

http's Introduction

Build Status

A composable, Future-based library for making HTTP requests.

package:http contains a set of high-level functions and classes that make it easy to consume HTTP resources. It's multi-platform, and supports mobile, desktop, and the browser.

Packages

Package Description Version
http A composable, multi-platform, Future-based API for HTTP requests. pub package
http_client_conformance_tests A library that tests whether implementations of package:http's Client class behave as expected.
cronet_http An Android Flutter plugin that provides access to the Cronet HTTP client. pub package
cupertino_http A macOS/iOS Flutter plugin that provides access to the Foundation URL Loading System. pub package
flutter_http_example An Flutter app that demonstrates how to configure and use package:http.

Contributing

If you'd like to contribute to any of these packages, see the Contributing Guide.

http's People

Contributors

aam avatar alex-james-dev avatar alexv525 avatar anikate-de avatar athomas avatar bahaafathi avatar brianquinlan avatar chalin avatar dependabot[bot] avatar derekxu16 avatar devoncarew avatar dgrove avatar floitschg avatar gramster avatar hosseinyousefi avatar jakemac53 avatar johnryan-wf avatar jonasfj avatar kevmoo avatar lrhn avatar mhausner avatar mit-mit avatar munificent avatar natebosch avatar nex3 avatar sethladd avatar sgjesse avatar srawlins avatar whesse avatar yjbanov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

http's Issues

url size limitation

Reproduce

import 'package:http/http.dart';

main() {
  Client client = new IOClient();
  String str = "a" * 10000;
  client.post("http://localhost:1338/$str").then((Response res) {
    print(res.statusCode);
    print(res.body);
    client.close();
  }, onError: (error) {
    print(error);
    client.close();
  });
}

nc -l 1338

I am getting this error but I cannot catch it.

Unhandled exception:
HttpException: Headers size exceeded the of '8192' bytes
#0      _rootHandleUncaughtError.<anonymous closure> (dart:async/zone.dart:1138)
#1      _microtaskLoop (dart:async/schedule_microtask.dart:41)
#2      _startMicrotaskLoop (dart:async/schedule_microtask.dart:50)
#3      _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:96)
#4      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:149)

Is it the correct behaviour, I am dealing with an api that need a lot of data in the url, any workaround ?

Something is wrong with MultipartRequest

Today I tried make a request to https://api.telegram.org with MultipartRequest, but I did not succeed. Meanwhile, in the postman chrome application it working fine.

What am I doing wrong?

Postman

2017-03-03-113540_902x710_scrot

Http package

I tried run this code:

import 'dart:async';
import 'package:http/http.dart' as http;

Future main() async {
  final url = Uri.parse('https://api.telegram.org/bot123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11/getMe');
  final request = new http.MultipartRequest('POST', url);
  request.fields['Name'] = 'John';
  final response = await request.send();
  print(await response.stream.bytesToString());
}

but got the 504 error:

<html>
<head><title>504 Gateway Time-out</title></head>
<body bgcolor="white">
<center><h1>504 Gateway Time-out</h1></center>
<hr><center>nginx/1.10.0</center>
</body>
</html>

pkg/http headers should be case-insensitive

Originally opened as dart-lang/sdk#17062

This issue was originally filed by [email protected]


When using the code snippet below, the content-type header is overloaded by "text/plain".

  import 'package:http/http.dart' as Http;
  Http.post(url, body: postData, headers: { "Content-Type": "text/xml" })

As we can't set _contentType from Request class, could you add 'content-type' in basic client requests also ? (see 'request.dart' source code)

  set body(String value) {
    bodyBytes = encoding.encode(value);
    var contentType = _contentType;
    if (contentType == null) {
      contentType = new ContentType("text", "plain", charset: encoding.name);
    } else if (contentType.charset == null) {
      contentType = new ContentType(contentType.primaryType,
                                    contentType.subType,
                                    charset: encoding.name,
                                    parameters: contentType.parameters);
    }
    _contentType = contentType;
  }

Environement
Dart VM version: 1.1.3 (Thu Feb 06 00:05:52 2014) on "windows_ia32"
http package: http-0.9.2+3

Http package fails to read an URL

<img src="https://avatars.githubusercontent.com/u/148256?v=3" align="left" width="96" height="96"hspace="10"> Issue by kaisellgren
Originally opened as dart-lang/sdk#9675


This code using the HTTP package fails:

    http.read('https://www.chms.edu.mx/')

The result is:

Uncaught Error: SocketIOException: RawSecureSocket error (Unexpected handshake error in client) (OS Error: errno = -8181)
Unhandled exception:
SocketIOException: RawSecureSocket error (Unexpected handshake error in client) (OS Error: errno = -8181)

­0 _FutureImpl._scheduleUnhandledError.<anonymous closure> (dart:async:347:9)

­1 Timer.Timer.<anonymous closure> (dart:async-patch:11:15)

­2 _Timer._createTimerHandler._handleTimeout (dart:io:6031:28)

­3 _Timer._createTimerHandler._handleTimeout (dart:io:6039:7)

­4 _Timer._createTimerHandler.<anonymous closure> (dart:io:6047:23)

­5 _ReceivePortImpl._handleMessage (dart:isolate-patch:40:92)

BrowserClient throws an error while HttpRequest does not

Using BrowserClient instead of HttpRequest throws a spurious error: "Invalid status code 0" even when the http response code is 200

--------------EXCEPTION------------------------------------------
EXCEPTION: Invalid argument(s): Invalid status code 0.

VM14600:1 STACKTRACE:(anonymous function) @ VM14600:1
VM14600:1 package:http/src/base_response.dart 48:7                 BaseResponse.BaseResponse
package:http/src/streamed_response.dart 31:7             StreamedResponse.StreamedResponse
package:http/browser_client.dart 64:32                   BrowserClient.send.<async>.<fn>.<fn>
package:stack_trace                                      StackZoneSpecification.registerUnaryCallback.<fn>
package:angular2/src/core/zone/ng_zone_impl.dart 162:40  NgZoneImpl._runUnary.<fn>
dart:async                                               _ZoneDelegate.run
package:angular2/src/core/zone/ng_zone_impl.dart 155:21  NgZoneImpl._run
package:angular2/src/core/zone/ng_zone_impl.dart 162:7   NgZoneImpl._runUnary
package:stack_trace                                      StackZoneSpecification.registerUnaryCallback.<fn>
package:angular2/src/core/zone/ng_zone_impl.dart 162:40  NgZoneImpl._runUnary.<fn>
dart:async                                               _ZoneDelegate.run
package:angular2/src/core/zone/ng_zone_impl.dart 155:21  NgZoneImpl._run
package:angular2/src/core/zone/ng_zone_impl.dart 162:7   NgZoneImpl._runUnary


-----async gap-----
dart:async                                               _Future.then
package:http/browser_client.dart 62:27                   BrowserClient.send.<async>.<fn>
package:stack_trace                                      StackZoneSpecification.registerUnaryCallback.<fn>
package:angular2/src/core/zone/ng_zone_impl.dart 162:40  NgZoneImpl._runUnary.<fn>
dart:async                                               _ZoneDelegate.run
package:angular2/src/core/zone/ng_zone_impl.dart 155:21  NgZoneImpl._run
package:angular2/src/core/zone/ng_zone_impl.dart 162:7   NgZoneImpl._runUnary
package:stack_trace                                      StackZoneSpecification.registerUnaryCallback.<fn>
package:angular2/src/core/zone/ng_zone_impl.dart 162:40  NgZoneImpl._runUnary.<fn>
dart:async                                               _ZoneDelegate.run
package:angular2/src/core/zone/ng_zone_impl.dart 155:21  NgZoneImpl._run
package:angular2/src/core/zone/ng_zone_impl.dart 162:7   NgZoneImpl._runUnary


-----async gap-----
dart:async                                               _Future.then
package:http/browser_client.dart 56:22                   BrowserClient.send.<async>
package:stack_trace                                      StackZoneSpecification.registerUnaryCallback.<fn>
package:angular2/src/core/zone/ng_zone_impl.dart 162:40  NgZoneImpl._runUnary.<fn>
dart:async                                               _ZoneDelegate.run
package:angular2/src/core/zone/ng_zone_impl.dart 155:21  NgZoneImpl._run
package:angular2/src/core/zone/ng_zone_impl.dart 162:7   NgZoneImpl._runUnary
dart:async                                               _Future._asyncComplete.<fn>
package:angular2/src/core/zone/ng_zone_impl.dart 176:11  NgZoneImpl._scheduleMicrotask.<fn>
dart:async                                               _ZoneDelegate.run
package:angular2/src/core/zone/ng_zone_impl.dart 155:21  NgZoneImpl._run


-----async gap-----
dart:async                                               _asyncThenWrapperHelper
package:http/browser_client.dart                         BrowserClient.send
package:http/src/base_client.dart 171:38                 BaseClient._sendUnstreamed.<async>
dart:async                                               _ZoneDelegate.run
package:angular2/src/core/zone/ng_zone_impl.dart 155:21  NgZoneImpl._run
dart:async                                               _CustomZone.bindCallback.<fn>
package:angular2/src/core/zone/ng_zone_impl.dart 176:11  NgZoneImpl._scheduleMicrotask.<fn>
dart:async                                               _ZoneDelegate.run
package:angular2/src/core/zone/ng_zone_impl.dart 155:21  NgZoneImpl._run


-----async gap-----
dart:async                                                                  Future.Future.microtask
package:http/src/base_client.dart                                           BaseClient._sendUnstreamed
package:http/src/base_client.dart 34:5                                      BaseClient.get

Add an option to disable or change URI encoding in HTTP package

<img src="https://avatars.githubusercontent.com/u/148256?v=3" align="left" width="96" height="96"hspace="10"> Issue by kaisellgren
Originally opened as dart-lang/sdk#10475


Currently as it stands, the HTTP package uses encodeUriComponent() from dart:uri to encode all fields.

This is not good when writing something like OAuth 1 lib for Twitter which happens to be what I/we are doing right now.

Instead, I have a fully RFC 3986 compliant percentage encoder, which Twitter OAuth API likes. The problem is that there is no way to disable or switch the encoding that is used.

Can we either add an option to disable it or to provide a callback for encoding?

Add request body to http request function in http library

<img src="https://avatars.githubusercontent.com/u/1688987?v=3" align="left" width="96" height="96"hspace="10"> Issue by luisvt
Originally opened as dart-lang/sdk#20839


Add the ability to send http request body to delete function on http library (https://pub.dartlang.org/packages/http).

I was trying to use next code:

      delete('http://127.0.0.1:4040/persons', body: '[1,2]').then((Response response) {
        //... other code ...
      });

I realize that it wasn't possible to do it since the function doesn't support a request body. So instead, I should use next code:

      new Client().send(new Request('DELETE', new Uri.http('127.0.0.1:4040', '/persons'))..body = '[1,2]').then((response) {
        //... other code ...
      });

Although is not a big problem on doing in the second way all the time, it would be great to be able on doing in the first way.

I know that you should modify lines 107 and 108 on file http from this:

  Future<Uint8List> delete(url, {Map<String, String> headers}) =>
    _withClient((client) => client.delete(url, headers: headers));

to this:

  Future<Uint8List> delete(url, {Map<String, String> headers, body}) =>
    _withClient((client) => client.delete(url, headers: headers, body));

also line 96 on client.dart from this:

  Future<Response> delete(url, {Map<String, String> headers});

to this:
  Future<Response> delete(url, {Map<String, String> headers, body});

and also lines 85 and 86 in base_client.dart from this:

  Future<Response> delete(url, {Map<String, String> headers}) =>
    _sendUnstreamed("DELETE", url, headers);

to this:

  Future<Response> delete(url, {Map<String, String> headers, body}) =>
    _sendUnstreamed("DELETE", url, headers, body);

Please allow us to mock the Client used by _withClient

We would like to be able to inject a client into the http package (e.g. the MockClient obtained from http/testing) such that the top-level methods such as "get" and "head" and so forth will use the mock client instead of a brand new Client.

We had previously implemented this by forking http and changing it as follows:
https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/http/client.dart#L32

We would like to just use the http package directly now, but without this way to inject a MockClient, we have the problem that anyone using the convenience methods like http.get() will end up doing actual network traffic in our tests instead of hitting our mock.

XMLHttpRequest error

From @SadovovAlex on March 14, 2017 12:7

if response this format or other json:
{"listFias":[],"status":"NotFound"}

i recieved error:
XMLHttpRequest cannot load http://0001qwerty02:8888

  var client = new BrowserClient();
  var url = '/whatsit/create';
  var response =
      await client.post(url, body: {'name': 'doodle', 'color': 'blue'});
  print('Response status: ${response.statusCode}');
  print('Response body: ${response.body}');

Copied from original issue: dart-lang/sdk#29068

There should be a library like this for WebSockets

I know this is not exactly the right place to request this feature, but it's a general Dart one that best related to this package.

WebSockets in Dart are hell. There is no unified interface for VM and Browser and it makes it impossible to create packages that work on top of WebSockets (which are platform-agnostic for the remainder of the package).

A library like this that provides a unified interface for both is really great and I think having one for WebSockets (package:websockets f.e.) would be very useful.

Http package does not expose HttpClient capabilities but keeps the backing instance private at the same time

Originally opened as dart-lang/sdk#18871

This issue was originally filed by [email protected]


What steps will reproduce the problem?

  1. Import the built in package with: import 'package:http/http.dart';
  2. Try to issue a request against a host which has SSL problems, in my case SEC_ERROR_UNKNOWN_ISSUER ( see https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/SSL_functions/sslerr.html )
  3. Watch it fail with a handshake problem

What is the expected output? What do you see instead?

I'd expect the http package to expose the setter for the backing HttpClient badCertificateCallback somehow.

To solve my use-case the easiest would be to publicise the currently private variable ( called _inner in io_client.dart ) but I can see how some people would oppose that.

What version of the product are you using? On what operating system?
Dart Stable 1.3.6, it's the same in 1.4.0-edge.36282
OS X Mavericks 10.9.2

Please provide any additional information below.

server side api has Cookie, please add to client side api

<img src="https://avatars.githubusercontent.com/u/5606587?v=3" align="left" width="96" height="96"hspace="10"> Issue by trinarytree
Originally opened as dart-lang/sdk#19005


https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-io.Cookie
seems to only be available to the server.

that forces other libraries, e.g.
https://docs.angulardart.org/#angular-core.Cookies to implement their own;
or (gasp) the app level code must use the document.cookie api directly.

the angular one isn't nearly as comprehensive as the dart one, e.g.
it doesn't fully support cookie path or expiration dates
(it has really limited support for cookie path).
but really, angular shouldn't have to write such a library,
it should be in dart. you guys already wrote 90% of the code,
you should just share some of it with the client side.
i don't want to have to implement my own crazy DateTime to cookie-date converters.

Remove dart:mirror usage from package:http

A change to the dart2js compiler introduced a warning on mirror usage in dart code -- see Emit warning on import of dart:mirrors.. According to the warning, users will be forced to pass an additional flag to the dart2js compiler when their code is using dart:mirrors. This affects all users of package:http.

When compiling the following example

import 'package:http/http.dart';
main()=> print("hello");

dart2js will print out the following warning:

Warning: 
****************************************************************
* WARNING: dart:mirrors support in dart2js is experimental,
*          and not recommended.
*          This implementation of mirrors is incomplete,
*          and often greatly increases the size of the generated
*          JavaScript code.
*
* Your app imports dart:mirrors via:
*   x.dart => package:http => dart:mirrors
*
* Starting with Dart 1.9, you must use the
* --enable-experimental-mirrors command-line flag to opt-in.
* You can begin using this flag now if mirrors support is critical.
*
* To learn what to do next, please visit:
*    http://dartlang.org/dart2js-reflection
****************************************************************

That flag does not seem to be enforced as of SDK version 1.9.0-dev.1.0+google3-trunk, but that seems to be only a matter of time.

http headers Content-Type problems

Originally opened as dart-lang/sdk#17405

This issue was originally filed by [email protected]


A Content-Type header is ignored when sending http.post.

If I call http.post with a header "Content-Type", the server doesn't get the value specified if there is also a body. Instead, it always gets "text/plain; charset=utf-8".

If I change the header key to "content-type", everything works as expected.

There are several issues here.

  1. I would expect the header key to be used case-insensitive.
  2. Requests set body has as side-effect that the _contentType is set.

This side-effect is documented, however it explicitly mentions "Content-Type". And so does Requests ContentType get \_contentType.

I've attached two source files to demonstrate the problem.


Attachments:
httpheadersserver.dart (288 Bytes)
httpheadersclient.dart (243 Bytes)
pubspec.yaml (91 Bytes)

Should streamed_request_test.dart run?

I'm working on a package that includes a transformer (Reflectable), so I need to run tests that have been transformed. The situation is very similar to that of http/build/test/io/streamed_request_test.dart.

However, I have the problem that the build/... tree does not contain 'packages' directories (nor symlinks) in nested directories, only in build/test. This makes the tests fail in Reflectable, so I wondered why streamed_request_test.dart does not fail in http (http is not red on the package-bots). I cannot see any reason in http/.status why this test should not run, and it does indeed fail when I 'git clone' the http package, 'pub get', 'pub build --mode=debug test', and run this:

~/tmp/tmprepos/http(master)$ dart test/io/streamed_request_test.dart    [15:12]
unittest-suite-wait-for-done
PASS: contentLength controls the Content-Length header
PASS: contentLength defaults to sending no Content-Length
PASS: .send() with a response with no content length

All 3 tests passed.
unittest-suite-success
~/tmp/tmprepos/http(master)$ dart build/test/io/streamed_request_test.dart
Unhandled exception:
Uncaught Error: Load Error: FileSystemException: Cannot open file, path = '/usr/local/google/home/eernst/tmp/tmprepos/http/build/test/io/packages/http/http.dart' (OS Error: No such file or directory, errno = 2)
Stack Trace:
#0      _asyncLoadErrorCallback (dart:_builtin:335)
#1      _asyncLoadError (dart:_builtin:354)
#2      _loadDataAsyncDartIO.<anonymous closure> (dart:_builtin:76)
#3      _RootZone.runUnary (dart:async/zone.dart:1155)
#4      _Future._propagateToListeners.handleError (dart:async/future_impl.dart:515)
#5      _Future._propagateToListeners (dart:async/future_impl.dart:570)
#6      _Future._completeWithValue (dart:async/future_impl.dart:358)
#7      _Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:412)
#8      _asyncRunCallbackLoop (dart:async/schedule_microtask.dart:41)
#9      _asyncRunCallback (dart:async/schedule_microtask.dart:48)
#10     _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:96)
#11     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:143)

#0      _rootHandleUncaughtError.<anonymous closure> (dart:async/zone.dart:886)
#1      _asyncRunCallbackLoop (dart:async/schedule_microtask.dart:41)
#2      _asyncRunCallback (dart:async/schedule_microtask.dart:48)
#3      _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:96)
#4      _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:143)

So I was wondering: Is it a bug that this test (build/test/io/streamed_request_test.dart) is never executed, or does it somehow run successfully on the package bots? In the latter case, I'd like to know how you do it, and in the former case you might want to check it out. ;-)

I've notified the pub-dartlang folks on https://code.google.com/p/dart/issues/detail?id=22677.

Update URI for bug reports

The pub package's documentation states that bugs should be filed on http://dartbug.com/new.
That URI should be updated to the http package's issue tracker.

Dependency on dart:io

The latest update 0.11.3+10 which removes the mirrors dependency, adds a dependency to "dart:io" which the BrowserClient can see (via BaseClient -> Client -> IOClient). Whilst it still works when compiled to javascript, when running in Dartium it throws the following error:

The requested built-in library is not available on Dartium.'package:http/src/io_client.dart': error: line 6 pos 1: library handler failed
import 'dart:io';
^: package:http/src/io_client.dart

(MultipartRequest) Content-Transfer-Encoding header is probably unnecessary / wrong

Usually an unnecessary header doesn't hurt. But in my case the browser aborts an xmlhttprequest:

XMLHttpRequest cannot load.... Request header field content-transfer-encoding is not allowed by Access-Control-Allow-Headers in preflight response.

Apparently Content-Transfer-Encoding is not a valid http header anyways:
stackoverflow

Response I got from the server when the Request method was OPTIONS:

HTTP/1.1 204 No Content
Date: Wed, 06 Jul 2016 18:27:29 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, DELETE, PUT
Access-Control-Allow-Headers: Content-Type, api_key, Authorization
Allow: OPTIONS,POST
Connection: close
Server: Jetty(9.2.9.v20150224)

http post a map object using application/json content-type

Originally opened as dart-lang/sdk#17636

This issue was originally filed by [email protected]


I am encountering a problem trying to use the "package:http/http.dart' pub package to post some JSON data to a web service. I have formatted the data correctly (which I confirmed by posting using the Advanced REST Client extension for Chrome) and the only difference is the Content-Type is forced to the wrong type (the web service only accepts "application/json"):

If body is a Map, it's encoded as form fields using encoding. The content-type of the request will be set to "application/x-www-form-urlencoded"; this cannot be overridden.

The documentation suggests:

For more fine-grained control over the request, use Request or StreamedRequest instead.

Why is the post content type limited to only form-urlencoded? Can the pub package be fixed to set the content type dynamically?

strong mode errors

Some simple issues from ddc:

super call must be last in an initializer list (see http://goo.gl/q1T4BB): super(method, url) (package:http/src/multipart_request.dart, line 52, col 7)
super call must be last in an initializer list (see http://goo.gl/q1T4BB): super(method, url) (package:http/src/request.dart, line 135, col 7)
super call must be last in an initializer list (see http://goo.gl/q1T4BB): super(method, url) (package:http/src/streamed_request.dart, line 33, col 7)
super call must be last in an initializer list (see http://goo.gl/q1T4BB): super(statusCode, contentLength: contentLength, request: request, headers: headers, isRedirect: isRedirect, persistentConnection: persistentConnection, reasonPhrase: reasonPhrase) (package:http/src/streamed_response.dart, line 32, col 7)

MultipartRequest of the Http package percent-encodes form field names

Originally opened as dart-lang/sdk#17899

This issue was originally filed by [email protected]


What steps will reproduce the problem?

  1. Create an instance of MultipartRequest as your HTTP request.
  2. Add a form field to your request object created in step 1 with a name that contains non-alphanumeric (but still ASCII contained) characters, such as the string: "login[username]".
  3. POST the form, for example with this code: new http.Client().send(yourRequestObject);

What is the expected output? What do you see instead?
The form field's name should stay untouched, but the braces get percent encoded and the request gets rejected by the server (tested with PHP/5.4.4-14+deb7u8 plus nginx/1.2.1)

What version of the product are you using? On what operating system?
OS X 10.9.2
Dart SDK 1.2.0

Please provide any additional information below.

The source of the problem is this code snippet from packages/http/src/multipart_request.dart
var header = 'content-disposition: form-data; name="${Uri.encodeFull(name)}"';

The previous snippet's comment (pasted below) states that this is intended and the goal was to reproduce the behaviour of browsers.
Still, posting a form with the mentioned field name included, both Chrome and Firefox will leave it as is, and the POST will be accepted by the same back-end mentioned above.

// http://tools.ietf.org/html/rfc2388 mandates some complex encodings for
// field names and file names, but in practice user agents seem to just
// URL-encode them so we do the same.

I understand that implementing the 'complex encodings' can be kind of a grunt work, without too much leverage. But even simply leaving out the encoding would be better for my use-case.

I also wonder if there is already a well written utility class exactly for the mentioned 'complex encoding' somewhere in the chromium source. If yes, that probably could help a lot, simplifying the task to a C => Dart translation, just guessing here.

Anyways, from my side the only goal would be to make the same forms work that are working well on the major browsers already, maybe those aren't even RFC compliant either.

Peter

http library should redefine some of the enums from 'dart:io'

Originally opened as dart-lang/sdk#18746

This issue was originally filed by [email protected]


Now that the http library supports both browser and console contexts, libraries intending to use the library to provide requests are unable to use some of the useful enums defined in 'dart:io', (specific to my use case, HttpHeaders and HttpStatus).

It would be useful if the http library could redefine or reexport some of these classes.

Request set bodyFields, need to be able to have List<String> for a map value

From @rwrozelle on December 14, 2016 14:5

I need to be able to set bodyFields with a map that has multiple values for a single key, so map would be Map<String, Object> where Object would be either a String or List<String> at runtime. Here is an example map: {q: *:*, start: 0, rows: 0, facet: true, stats: true, stats.field: [{!countDistinct=true }vin, {!countDistinct=true }veh_year]}

Here is sample code of changes I would like, this is example code only, implementation could be a lot better:

//http 0.11.3+9/lib/src/request.dart - change Map input from <String, String> to <String, Object>
  set bodyFields(Map<String, Object> fields) {
    var contentType = _contentType;
    if (contentType == null) {
      _contentType = new MediaType("application", "x-www-form-urlencoded");
    } else if (contentType.mimeType != "application/x-www-form-urlencoded") {
      throw new StateError('Cannot set the body fields of a Request with '
          'content-type "${contentType.mimeType}".');
    }

    this.body = mapToQuery(fields, encoding: encoding);
  }

//http 0.11.3+9/lib/src/utils.dart - rewrite to put key in multiple times when value is a list.
  /// Converts a [Map] from parameter names to values to a URL query string.
  ///
  ///     mapToQuery({"foo": "bar", "baz": "bang"});
  ///     //=> "foo=bar&baz=bang"
  String mapToQuery(Map<String, Object> map, {Encoding encoding}) {
    String retStr = '';
    String delimiter = '';
    var keys = map.keys;
    for (String key in keys) {
      var value = map[key];
      if (value is List) {
        for (String subvalue in value) {
          retStr +="${delimiter}${key}=${subvalue}";
          delimiter='&';
        }
      }
      else {
        retStr +="${delimiter}${key}=${value}";
        delimiter='&';
      }
    }
    return retStr;
  }

Copied from original issue: dart-lang/sdk#28098

Unable to send post form using http Library because of call of Uri.encodeQueryComponent with 2 parameters instead 1 ...

<img src="https://avatars.githubusercontent.com/u/6410144?v=3" align="left" width="96" height="96"hspace="10"> Issue by ioull
Originally opened as dart-lang/sdk#16131


What steps will reproduce the problem?
create a dart file like this :
import 'package:http/http.dart' as http;

main() {
  http.post('http://httpbin.org/post', body: {'key1': 'value1', 'key2': 'value2'}).then((response) {
    print("Response status: ${response.statusCode}");
    print("Response body: ${response.body}");
  });
}

What is the expected output? What do you see instead?
I expect to get a request with form data ... BUT i got
Unhandled exception:
No static method 'encodeQueryComponent' declared in class 'Uri'.

NoSuchMethodError: incorrect number of arguments passed to method named 'encodeQueryComponent'
Receiver: Type: class 'Uri'
Tried calling: encodeQueryComponent("key1", encoding: Instance of 'Utf8Codec')
Found: encodeQueryComponent(String)

­0 _rootHandleUncaughtError.<anonymous closure>.<anonymous closure> (dart:async/zone.dart:677)

­1 _asyncRunCallback (dart:async/schedule_microtask.dart:18)

­2 _asyncRunCallback (dart:async/schedule_microtask.dart:21)

­3 _createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:11)

­4 _Timer._createTimerHandler._handleTimeout (timer_impl.dart:151)

­5 _Timer._createTimerHandler._handleTimeout (timer_impl.dart:159)

­6 _Timer._createTimerHandler._handleTimeout (timer_impl.dart:159)

­7 _Timer._createTimerHandler.<anonymous closure> (timer_impl.dart:166)

­8 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:93)

What version of the product are you using? On what operating system?
http-0.9.2+1 library

Please provide any additional information below.

A delay occurs when program terminates using IOClient

I tried to run these codes.

This program don't uses IOClient.

import 'package:http/http.dart' as http;

main() {
  http.get("https://www.dartlang.org").then((response) {
        print(response.body);
  });
}
<!doctype html>
~
</html>
[Finished in 2.3s]

This program uses IOClient.

import 'package:http/http.dart' as http;

main() {
  http.IOClient ioClient = new http.IOClient();
  ioClient.get("https://www.dartlang.org").then((response) {
    print(response.body);
  });
}
<!doctype html>
~
</html>
[Finished in 16.6s]

What to do to solve this problem?

Adding a factory method to create a request/response (http package) from a request/response (io package)

I think it could be cool to be able to create one of these when I'm using another framework that's using io.HttpResponse, I like the Future api you provide.

ie: using redstone.dart

import 'package:http/http.dart' as http;
import 'dart:io';

// this returns an HttpResponse from dart:io
HttpResponse resp = await app.dispatch(req);
// what I'd like to do then
http.HttpResponse myResponse = new http.HttpResponse.fromIoResponse(resp);
// use it ..
String body = await myResponse.body;

http.head() can return empty unhandled exception

var response = await http.head('http://v.youku.com/v_show/id_XOTUwODY0NDky.html').catchError(print);
        print(response);

The error is empty. Remove the catchError and it reports as Unhandled Exception:.

add Timeout functionality for http package

Originally opened as dart-lang/sdk#19831

This issue was originally filed by [email protected]


What steps will clearly show the issue / need for enhancement?

  1. when making http requests you usually want to timeout the request after a reasonable amount of time (usually in the region of seconds)
  2. it would be great to have away to specify timeout as Duration when making a http request via the http/browser client/http client classes.

What version of the product are you using? On what operating system?
Dart 1.5.1, http 0.11.1+1

BrowserClient doesn't have a way to set withCredentials=true so Cookies aren't being sent accros domains.

Originally opened as dart-lang/sdk#23088

This issue was originally filed by [email protected]


I don't see any way currently to set withCredentials=true on BrowserClient so that I can send cookies across domains (this is especially important in dev as I'm developing on one server and the dart client is on another server which I believe is a common use-case scenario).

What steps will clearly show the issue / need for enhancement?
1: I can easily allow cross-domain communication by setting CORS headers on the server side, as soon as I want to send back a cookie from the server to maintain state on the client side, I can't do it. I've looked at HTML5 localstorage, but that's not secure, I need to be able to set Cookies with HttpOnly and Secure flags so that JavaScript can't access it.
2: I see angular.dart made provision for the withCredentials flag to allow sending cookies across domains.

What is the current output?
Seeing cookie headers coming back from the server, but not on the request.

What would you like to see instead?
Seeing cookie headers on both the request and response.

What version of the product are you using? On what operating system?
Dart 1.9

Please provide any additional information below.
See my StackOverflow post: http://stackoverflow.com/questions/29427203/dart-browserclient-post-not-including-my-cookies

package:http missing docs on dartdocs.org

Steps to reproduce:

  1. Go to https://pub.dartlang.org/packages/http
  2. Click the link under "Documentation" on the right

Expected result

I expect to see the API docs for package:http

Actual result

I get a 404.

Analysis

https://www.dartdocs.org/documentation/http/0.11.3%2B12/ lacks API docs. The most recent version with API docs appears to be 0.11.3+10:

https://www.dartdocs.org/documentation/http/0.11.3%2B10/

Perhaps this corresponded to the change in SDK requirements in package:http and dartdocs.org is using an old Dart SDK to generate the docs?

package:http abstracts request headers as a Map<string, string>; that does not work for repeating headers

Originally opened as dart-lang/sdk#21802

This issue was originally filed by [email protected]


Package http represents request headers as a Map<string, string>, both in requests as well as in responses. That does not work for repeating headers, In that case one needs to fold them into a single string. Which is not always practical or possible.

What steps will reproduce the problem?

The most problematic header is Set-Cookie since the concatenation of multiple cookies into one string is tricky to parse.

Please provide any additional information below.

Some browsers and libraries e.g. http.cookies in Python can deal with folded Set-Cookie headers.

RFC 6265 says "don't do that" (section 3)

performance issue on mac os x when using localhost in url

A simple request like getting the string "hello" using the http package from a shelf server running on the same host takes an unusually long time (5 seconds) when the url refers to localhost on my mac. The same connection takes less than 5 milliseconds on Chrome. The request takes less than 100 ms when the url uses 127.0.0.1 instead of localhost. I repeated the test on an Ubuntu Linux machine using localhost and it behaves as expected.

client

import 'package:http/http.dart' as http;

main(List<String> args) async {

    var client = new http.Client();

    Stopwatch sw = new Stopwatch();
    sw.start();

    var response = await client.get(Uri.parse("http://localhost:10080"));

    sw.stop();

    print('response received ${sw.elapsedMilliseconds}');
    client.close();



}

server

import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';

main(List<String> args) async {

  var handler = (Request r){
    return new Response.ok("hello");
  } ;

  var server = await serve(const Pipeline()
      .addMiddleware(logRequests())
      .addHandler(handler),  InternetAddress.ANY_IP_V4, 10080);

  print('Serving at http://${server.address.host}:${server.port}');

sdk: 1.19.1
mac os x: 10.11.6
http: 0.11.3+9
shelf: 0.6.5+3

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.