Giter VIP home page Giter VIP logo

http-request's Introduction

Http Request Build Status

A simple convenience library for using a HttpURLConnection to make requests and access the response.

This library is available under the MIT License.

Usage

The http-request library is available from Maven Central.

<dependency>
  <groupId>com.github.kevinsawicki</groupId>
  <artifactId>http-request</artifactId>
  <version>6.0</version>
</dependency>

Not using Maven? Simply copy the HttpRequest class into your project, update the package declaration, and you are good to go.

Javadocs are available here.

FAQ

Who uses this?

See here for a list of known projects using this library.

Why was this written?

This library was written to make HTTP requests simple and easy when using a HttpURLConnection.

Libraries like Apache HttpComponents are great but sometimes for either simplicity, or perhaps for the environment you are deploying to (Android), you just want to use a good old-fashioned HttpURLConnection. This library seeks to add convenience and common patterns to the act of making HTTP requests such as a fluid-interface for building requests and support for features such as multipart requests.

Bottom line: The single goal of this library is to improve the usability of the HttpURLConnection class.

What are the dependencies?

None. The goal of this library is to be a single class class with some inner static classes. The test project does require Jetty in order to test requests against an actual HTTP server implementation.

How are exceptions managed?

The HttpRequest class does not throw any checked exceptions, instead all low-level exceptions are wrapped up in a HttpRequestException which extends RuntimeException. You can access the underlying exception by catching HttpRequestException and calling getCause() which will always return the original IOException.

Are requests asynchronous?

No. The underlying HttpUrlConnection object that each HttpRequest object wraps has a synchronous API and therefore all methods on HttpRequest are also synchronous.

Therefore it is important to not use an HttpRequest object on the main thread of your application.

Here is a simple Android example of using it from an AsyncTask:

private class DownloadTask extends AsyncTask<String, Long, File> {
  protected File doInBackground(String... urls) {
    try {
      HttpRequest request =  HttpRequest.get(urls[0]);
      File file = null;
      if (request.ok()) {
        file = File.createTempFile("download", ".tmp");
        request.receive(file);
        publishProgress(file.length());
      }
      return file;
    } catch (HttpRequestException exception) {
      return null;
    }
  }

  protected void onProgressUpdate(Long... progress) {
    Log.d("MyApp", "Downloaded bytes: " + progress[0]);
  }

  protected void onPostExecute(File file) {
    if (file != null)
      Log.d("MyApp", "Downloaded file to: " + file.getAbsolutePath());
    else
      Log.d("MyApp", "Download failed");
  }
}

new DownloadTask().execute("http://google.com");

Examples

Perform a GET request and get the status of the response

int response = HttpRequest.get("http://google.com").code();

Perform a GET request and get the body of the response

String response = HttpRequest.get("http://google.com").body();
System.out.println("Response was: " + response);

Print the response of a GET request to standard out

HttpRequest.get("http://google.com").receive(System.out);

Adding query parameters

HttpRequest request = HttpRequest.get("http://google.com", true, 'q', "baseball gloves", "size", 100);
System.out.println(request.toString()); // GET http://google.com?q=baseball%20gloves&size=100

Using arrays as query parameters

int[] ids = new int[] { 22, 23 };
HttpRequest request = HttpRequest.get("http://google.com", true, "id", ids);
System.out.println(request.toString()); // GET http://google.com?id[]=22&id[]=23

Working with request/response headers

String contentType = HttpRequest.get("http://google.com")
                                .accept("application/json") //Sets request header
                                .contentType(); //Gets response header
System.out.println("Response content type was " + contentType);

Perform a POST request with some data and get the status of the response

int response = HttpRequest.post("http://google.com").send("name=kevin").code();

Authenticate using Basic authentication

int response = HttpRequest.get("http://google.com").basic("username", "p4ssw0rd").code();

Perform a multipart POST request

HttpRequest request = HttpRequest.post("http://google.com");
request.part("status[body]", "Making a multipart request");
request.part("status[image]", new File("/home/kevin/Pictures/ide.png"));
if (request.ok())
  System.out.println("Status was updated");

Perform a POST request with form data

Map<String, String> data = new HashMap<String, String>();
data.put("user", "A User");
data.put("state", "CA");
if (HttpRequest.post("http://google.com").form(data).created())
  System.out.println("User was created");

Copy body of response to a file

File output = new File("/output/request.out");
HttpRequest.get("http://google.com").receive(output);

Post contents of a file

File input = new File("/input/data.txt");
int response = HttpRequest.post("http://google.com").send(input).code();

Using entity tags for caching

File latest = new File("/data/cache.json");
HttpRequest request = HttpRequest.get("http://google.com");
//Copy response to file
request.receive(latest);
//Store eTag of response
String eTag = request.eTag();
//Later on check if changes exist
boolean unchanged = HttpRequest.get("http://google.com")
                               .ifNoneMatch(eTag)
                               .notModified();

Using gzip compression

HttpRequest request = HttpRequest.get("http://google.com");
//Tell server to gzip response and automatically uncompress
request.acceptGzipEncoding().uncompress(true);
String uncompressed = request.body();
System.out.println("Uncompressed response is: " + uncompressed);

Ignoring security when using HTTPS

HttpRequest request = HttpRequest.get("https://google.com");
//Accept all certificates
request.trustAllCerts();
//Accept all hostnames
request.trustAllHosts();

Configuring an HTTP proxy

HttpRequest request = HttpRequest.get("https://google.com");
//Configure proxy
request.useProxy("localhost", 8080);
//Optional proxy basic authentication
request.proxyBasic("username", "p4ssw0rd");

Following redirects

int code = HttpRequest.get("http://google.com").followRedirects(true).code();

Custom connection factory

Looking to use this library with OkHttp? Read here.

HttpRequest.setConnectionFactory(new ConnectionFactory() {

  public HttpURLConnection create(URL url) throws IOException {
    if (!"https".equals(url.getProtocol()))
      throw new IOException("Only secure requests are allowed");
    return (HttpURLConnection) url.openConnection();
  }

  public HttpURLConnection create(URL url, Proxy proxy) throws IOException {
    if (!"https".equals(url.getProtocol()))
      throw new IOException("Only secure requests are allowed");
    return (HttpURLConnection) url.openConnection(proxy);
  }
});

Contributors

http-request's People

Contributors

aried3r avatar bod avatar davidtpate avatar eddieringle avatar fs111 avatar henryju avatar jakewharton avatar jblievremont avatar kevinsawicki avatar levinotik avatar michael-wang avatar oskarhagberg avatar peterdavehello avatar seanjensengrey 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  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-request's Issues

Add Http.MaxConnections Property

Hitting an issue with the whole "Connections Reset by Peer" and I didn't see a wrapper method that already exists to set this property. Hoping to have it added similar to the other property wrappers.

/**
   * Set the 'http.maxConnections' & 'https.maxConnections' properties to the given value
   * value.
   * <p>
   * This setting will apply to all requests.
   *
   * @param value
   */
  public static void maxConnections(final int value) {
    setProperty("http.maxConnections", String.valueOf(value));
    setProperty("https.maxConnections", String.valueOf(value));
  }

POST on 2.3 not sending body

I have some code like this

HttpRequest.post(BASE_URL + mPath) .authorization("SharedKey " + API_KEY+":"+ authHeader) .contentType(HttpRequest.CONTENT_TYPE_JSON) .header("date-utc", getRfc1123DateString()) .header("token", mToken) .send(jsonData);

When executing on 4.0+ devices everything works fine, but on 2.3 devices it is failing. Digging around I found that the post headers included an extra newline in between authorization and contentType and that the jsonData was not being sent with the headers.

Is this possibly an issue with HttpURLConnection?

Post Request Headers

Can you help me how to add headers in Post request that looks like this:

Thank you!

POST form not returning a response

I'm posting to a Node/Express service and expecting a 201 with response content, but the library seems to respond almost immediately. The service is hit and performs the action, but debugging seems to show a response code of -1. I'm assuming my lack of knowledge of the framework is to blame, as I took a piece of code from the below StackOverflow post and was able to get both my 201 and response content back. Here's the code I'm using to post the response:

HttpRequest request = HttpRequest.post(url);
HashMap<String, String> data = new HashMap<String, String>();
data.put("email", _user.username);
data.put("imageurl", _user.imageUrl);

if (request.form(data).created()) {
    return null;
}

Stack Overflow post: http://stackoverflow.com/questions/4945321/not-getting-the-response-body-for-http-post-request-in-android

Import as android project

Hello, I had trouble setting up an android project to use maven in eclipse, I would like to get help regarding importing http-request in eclipse as android project

Oauth usage

how to use this library with an oauth library (signpost), especialy when performing a POST request, thanks

ByteArrayOutputStream no close?

public String body(final String charset) throws HttpRequestException {
    final ByteArrayOutputStream output = byteStream();
    try {
      copy(buffer(), output);
      return output.toString(getValidCharset(charset));
    } catch (IOException e) {
      throw new HttpRequestException(e);
    }
  }

Proxy Test Failure

When building the maven tests, the test HttpRequestTest.basicProxyAuthentication() fails. I'm not very familiar with Jetty, but it seems the "proxyCountingHandler" defined in ServerTestCase.setUp() is never called.

Running com.github.kevinsawicki.http.HttpRequestTest
2013-05-29 11:18:59.299:INFO:oejs.Server:jetty-8.1.9.v20130131
2013-05-29 11:18:59.338:INFO:oejs.AbstractConnector:Started [email protected]:41443
2013-05-29 11:18:59.357:INFO:oejs.Server:jetty-8.1.9.v20130131
2013-05-29 11:18:59.366:INFO:oejs.AbstractConnector:Started [email protected]:58866
Tests run: 145, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.578 sec <<< FAILURE!

Results :

Failed tests:   basicProxyAuthentication(com.github.kevinsawicki.http.HttpRequestTest): expected:<user> but was:<null>

Tests run: 147, Failures: 1, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO] 
[INFO] http-request ...................................... FAILURE [3.849s]
[INFO] http-request-parent ............................... SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.657s
[INFO] Finished at: Wed May 29 11:19:00 EDT 2013
[INFO] Final Memory: 14M/90M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test (default-test) on project http-request: There are test failures.
[ERROR] 
[ERROR] Please refer to /home/rossimo/http-request/lib/target/surefire-reports for the individual test results.
[ERROR] -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test (default-test) on project http-request: There are test failures.

Please refer to /home/rossimo/http-request/lib/target/surefire-reports for the individual test results.
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:213)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352)

sending json in payload not supported?

hi,
trying to do the equivalent of
curl http://URL -d '{JSON}'

cant find a way to do it. seems like all the requests here work on a key=value basis and there is no way to just send the Json in the payload.

currently doing it with Apaches HttpClient as below but would love to simplify my code using your package:

        HttpPost request = new HttpPost(url);
        String s = cmd.toString();
        StringEntity params = new StringEntity(s);
        request.addHeader(CONTENT_TYPE, APPLICATION_JSON);
        request.setEntity(params);
        httpClient.execute(request);

Image Upload Code sample ?

Hi Kevin,

First thanks for the good work for http-requeset lib which really shorten my android development time. It is easy to use to "get" data from the server. Yet I am also trying to post image file to the server as a multipart form post. For some reason I tried to follow your sample but it didnt work.

Here is my code:

HttpRequest request = HttpRequest.post("http://my.upload.endpoint.com");
request.part("event_id", 1);
request.part("creator_user_id", 21); //TODO change this
request.part("desc", "some desc");
request.part("photo", new File(uploadImagePath));

    if (request.ok()) {
        Toast.makeText(getApplicationContext(), "Photo Uploaded.", Toast.LENGTH_LONG).show();
    } else {
        uploadPhotoFailed();
    }

Am I using the lib correctly?

Thanks in Advance.

dev host internal set custom DNS programatically

On the internal RESTful testing sometimes their is a need to replace and entry in the /etc/hosts file programmatically for example

169.34.0.39 auth.api.dev.mycompany.com

if I get the run my tests on jenkins and can't change the hosts file their then I want to add something like

InetAddress address = null;
try {
        address = InetAddress.getByAddress("http://auth.api.dev.mycompany.com", new byte[] {169, 34, 0, 39});
    } catch (UnknownHostException e) {
        LOGGER.error(LogMessages.READOBJECT.toString(), e.getMessage());
    }
return address == null ? EnvMyCompany.baseUrl() : address.getHostName();

what would be a quick way to bind a host to a custom ip with HttpRequest

Is their patch support

I get errors when using it like this
/v1/users/ java.net.ProtocolException: Invalid HTTP method: PATCH

Debug Logging

Another very useful thing should be possibility to enable debug logging with every request and response as verbose log to the logcat. Something like that can by very useful for app debugging.

java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed out)

java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)
Caused by: com.github.kevinsawicki.http.HttpRequest$HttpRequestException: java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed out)
at com.github.kevinsawicki.http.HttpRequest$Operation.call(HttpRequest.java:667)
at com.github.kevinsawicki.http.HttpRequest.copy(HttpRequest.java:2524)
at com.github.kevinsawicki.http.HttpRequest.body(HttpRequest.java:1675)
at com.github.kevinsawicki.http.HttpRequest.body(HttpRequest.java:1690)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
... 4 more
Caused by: java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed out)
at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:545)
at libcore.io.IoBridge.recvfrom(IoBridge.java:509)
at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
at java.io.BufferedInputStream.read(BufferedInputStream.java:304)
at com.squareup.okhttp.internal.http.HttpTransport$ChunkedInputStream.read(HttpTransport.java:445)
at java.io.BufferedInputStream.read(BufferedInputStream.java:304)
at java.io.InputStream.read(InputStream.java:163)
at com.github.kevinsawicki.http.HttpRequest$8.run(HttpRequest.java:2530)
at com.github.kevinsawicki.http.HttpRequest$8.run(HttpRequest.java:2524)
at com.github.kevinsawicki.http.HttpRequest$Operation.call(HttpRequest.java:661)
... 12 more
Caused by: libcore.io.ErrnoException: recvfrom failed: ETIMEDOUT (Connection timed out)
at libcore.io.Posix.recvfromBytes(Native Method)
at libcore.io.Posix.recvfrom(Posix.java:140)
at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:164)
at libcore.io.IoBridge.recvfrom(IoBridge.java:506)
... 22 more

'output' field should be accessed using a protected accessor

currently if somebody wants to override openOutput() to say send compressed data, they cant assign to output cause its private and also cause no accessor is used throughout the code to access it. This means replacing a bunch of code just to modify the output stream creation.

The output field should be protected and accessed using getOutput() throughout the code.

split request builder and response to two classes

Now is very confusing that request builder use the same class ad result. So it allow to call for example. It is possible now write something like this

HttpRequest.post("").header("x","y");

I think that will be much more logical and programmer friendly if request builder will use different class than response.

About Upload Progress callback

Hi @kevinsawicki ,

May i ask something about Upload Progress?

It seem update the progress with quick, but after 100% i need to wait about 20 sec for 7mb file.

How it work? is that like this :
100 kb of 7000 kb > send to server > update upload progress > 200kb of 7000kb send to server > update upload progress and more... > close http

or

read local file till 100% then send to server > close http? current upload progress seem like this.

or it depends on server setting?

Any way i can cancel the upload http? i use req.disconnect(); seems no work, it still send to the server and return http 201.

Hope you can assist on this, thanks for great library agian 👍

Ignore HTTPS security for all the instances

Sometimes I use a proxy to check if I'm passing the right data to a HTTPS API, so I have to use this code:

HttpRequest request = HttpRequest.get("https://google.com");
//Accept all certificates
request.trustAllCerts();
//Accept all hostnames
request.trustAllHosts();

to make the connection work with the proxy.

Is there a way to make this persistent?

Like so:

if (DEBUG) {
    HttpRequest.trustAllCertsGlobally();
    HttpRequest.trustAllHostsGlobally();
}

Update README

I believe there is a typo in README under Using entity tags for caching section.
It should be request.receive(latest) instead of request.body(latest).

Error using the library

I get this error when I invoke the following code inside my Android app. I am using v4.2

HttpRequest request = HttpRequest.get(RestClient.AUTH_URL);

Error:

W/dalvikvm: VFY: unable to resolve static method 4110: Lcom/github/kevinsawicki/http/HttpRequest;.get(Ljava/lang/CharSequence;)Lcom/github/kevinsawicki/http/HttpRequest;

Java/SDK version info:
screen shot 2013-05-19 at 2 21 51 am

Use a checked exception

This not really an issue but more of a question.
(I am sorry if this was already discussed before.)
I was wondering why you made the design choice of wrapping all IOException into a RuntimeException.
Currently if a network problem occurs and your call is not inside a try/catch block, the app is going to crash.
That means you should use a try/catch block in most situations - but the compiler won't force you to do so. In other words, it is easy to forget to do it.
To me that looks like less compile-time checks, and more runtime potential crashes.

Any insight about this?

Thank you for this library, besides this bit I really like it :)

Default request configutation

One of the biggest issue of this library is absence of the possibility to pre configure request. I mean situation when I want to add some headers, url parameters or enable GZIP for all request.

Something like

HttpRequest.buildDefaults().
   .header("version", "1.0.0")
   .parameter("locale","en")
   .acceptGzipEncoding().uncompress(true);

will be great

Not Modified HTTP Response with Content-Encoding Header causes EOFException

I'm seeing an issue when the library is reading a response using the .code() method when the response is Not Modified (304) but includes the 'Content-Encoding: gzip' response header.

Stack looks like this:

W/System.err( 9061): Caused by: com.github.kevinsawicki.http.HttpRequest$HttpRequestException: java.io.EOFException
W/System.err( 9061): at com.github.kevinsawicki.http.HttpRequest.code(HttpRequest.java:1392)
W/System.err( 9061): at com.github.kevinsawicki.etag.CacheRequest.stream(CacheRequest.java:170)
W/System.err( 9061): at com.doapps.android.common.rcs.ResourceManager$ResourceRequestCallable.call(ResourceManager.java:98)
W/System.err( 9061): at com.doapps.android.common.rcs.ResourceManager$ResourceRequestCallable.call(ResourceManager.java:80)
W/System.err( 9061): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
W/System.err( 9061): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
W/System.err( 9061): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
W/System.err( 9061): at java.lang.Thread.run(Thread.java:856)
W/System.err( 9061): Caused by: java.io.EOFException
W/System.err( 9061): at java.util.zip.GZIPInputStream.readFully(GZIPInputStream.java:206)
W/System.err( 9061): at java.util.zip.GZIPInputStream.(GZIPInputStream.java:98)
W/System.err( 9061): at java.util.zip.GZIPInputStream.(GZIPInputStream.java:81)
W/System.err( 9061): at libcore.net.http.HttpEngine.initContentStream(HttpEngine.java:541)
W/System.err( 9061): at libcore.net.http.HttpEngine.readResponse(HttpEngine.java:844)
W/System.err( 9061): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:283)
W/System.err( 9061): at libcore.net.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:495)
W/System.err( 9061): at com.github.kevinsawicki.http.HttpRequest.code(HttpRequest.java:1390)
W/System.err( 9061): ... 7 more

It looks like the call to stream() is causing code() to be invoked and that getResponseCode() which, for some reason I don't really understand, attempts to decode the body of the 304 response with a gzip stream.

Looking at this, it looks like a bug in libcore.net.http but I'm not sure and was looking for a second opinion. I'm not sure how we'd know the connection was 304 without calling getResponseCode, nor why getResponseCode would end up trying to decode the responses body. I'm not even sure how to work-around this, but this is the ETag implementation in amazon's S3 so it seems like its going to be a common issue.

Example Response Headers

< HTTP/1.1 304 Not Modified
< x-amz-id-2: CB8VnZUX/AZnDbCpDoDtqigG+oJmNwA/mHxNuwNMZrrLmdbgKTfVH5o8kTDlwXLN
< x-amz-request-id: 575E9965093D180B
< Date: Tue, 06 Aug 2013 00:19:23 GMT
< Content-Encoding: gzip
< Last-Modified: Thu, 20 Jun 2013 15:48:01 GMT
< ETag: "49f4ddac92a3575c927cee634266701a"
< Server: AmazonS3

URL within ctor should be URI

Any reason to choose URL vs URI within the constructor? URL is terribly broken (equals and other shenanigans). Would you consider using uri.toUrl() and have the general contract against URI?

Default configuration

I already raised request for possibility to configure custom configuration per program. But I think that library should have some pre defined configurations.

Now is by default timeout set to 0, also accept-gzip compression is turned of by default. I think that this i dangerous and user must think about it, because timeout 0 will block application completly.

Headers in HttpRequest

I want to add headers to HttpRequest, i've tried to use header and parameter method but it did not worked for me, can you show some examples of usage?

About http param

Hi kevinsawicki,

Can i get some assist from you?

It about param for http :

eg:
Map<String, Object> params = new HashMap<String, Object>();
params.put("playlist[name]", "testNewPlaylist");
params.put("playlist[vid][]", "123");
params.put("playlist[vid][]", "456");

using post method, but server just received vid "123" only, vid "456" is missing.
HttpRequest.post(apiUrl, params, true).
trustAllCerts().trustAllHosts().
readTimeout(30000).connectTimeout(15000).
header("Authorization", "Token " + "token="" + acc.token + """);

eg2 :
upload file to server , i keep get 302 or 500 http status.
HttpRequest req = HttpRequest.post(testUrl).header("Authorization", "Token " + "token="" + acc.token + """);
File upload = new File(Environment.getExternalStorageDirectory() + "/testupload/up.mp4");
req.part("content[name]", upload);
req.part("type", "video/mp4");

i need convert curl to this http lib, any help will be appreciate 👍

curl -X POST -i https://testing.com/contents.json -F
"content[name]=@/home/testupload/Videos/up.mp4;type=video/mp4"

And great thanks for this lib, make my code lesser and life easy! 👍

Json with Post

Hy, I want to send this json :
{
"uid" : App.RequestManager.genUID(),
"rctrls" : [ {
"rctrl" : "BcpLonNetwork/RCL_PFC_207/Bureau5",
"val" : {
"OCC" : "OC_UNOCC"
}
}]
}

So i do this :
request = HttpRequest.post(url).contentType("json").basic("login", "pass").send(params.toString());

I also try with form but i can't make a map with this json object because i have an array.

But it doesn't work plz help me :)

no way to iterate over all response headers

no way to iterate over all response headers

It would be nice if I could get all the headers returned by a server. I am using http-request to proxy some back end services and it returns non-standard headers that should make it back to the client.

Add callback to get upload progress

Thanks for the great library, been using it a lot in my projects!

However, for my current app I'm uploading large-ish files (5-15MB) via POST. While I can display a spinning icon to indicate progress, I'd love to have a callback of some sorts returning the already written bytes to use an actual progress bar for better feedback for the user.

Looking at the code, I guess the copy() functions are where one would be able to grab the progress. Any chance of that getting into the library?

Problem when encoding the '+' charcter

When using HttpRequest.get() with encode parameter to 'true', the '+' (for instance in /my-server/my-action?a-date=2013-01-01T00:00:00+0100) is not encoded to "%2B", but with a blank character.
The same when using HttpRequest.post().

Thanks!

how can i get url after redirect?

I use http-request for Android.
After pass get-request to server, it automatically redirected me to another url and returns response. Response contains relative address from redirected url.
How can I get url from redirected request?

Cookie-based Session persistence

It seems that the HttpRequest doesn't support keeping a session cookie around for subsequent requests because each one is a new connection. Is there a way to deal with this? For example, my server responds to a login request with the JSON of the user along with a Set-Cookie PHPSESSIONKEY = d0afdufahodf. It then looks for that PHPSESSIONKEY in subsequent requests for the user's data, so I need my requests to have that cookie set.

Is there a way to POST using JSON?

I know I can make a post with the DefaultHttpClient for JSON (http://stackoverflow.com/questions/6533234/how-to-make-httppost-call-with-json-encoded-body), but I'd like to use http-request and can't figure out how to do it. So far what I did was cast the JSON to a Map<String, String>, but that has unfortunate side effects, such as doing away with native arrays and numbers. I'm trying to figure out how to use http-request with request.form or something similar.

Can I use this to set up a web cam?

Hello,
I would like to know if I can use this to set up a web cam, i.e., using a smartphone as the remote camera and taking images of around 600x480 at 15f/s, and use this smartphone as a server sending out images, so that I can use PC or phones in the same Local WIFI to check the images?
Thanks

POST Request

Can you help send POST request look like this:
"user"=>{"email"=>"the email", "password"=>"the password"}
Im currently a beginner in HTTP POST Request, I'm targeting Rails Server.
Thank you!

non latin characters

How can i send POST request with non latin characters?
You need to implement somethig like this:
request.part(name , new StringEntity(body, HTTP.UTF_8));

Perform Login

hello, well this is not really an issue but im working with foursquare api and i was wondering if i can use this neat library to login to a website (i.e https://foursquare.com/login) and then use http get requests and monitor the response while logged in.
Will this do the job or do i have to use a more advanced library for logins like jsoup?

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.