GithubHelp home page GithubHelp logo

hgoebl / davidwebb Goto Github PK

View Code? Open in Web Editor NEW
126.0 126.0 41.0 665 KB

Lightweight Java HTTP-Client for calling JSON REST-Services (especially for Android)

Home Page: https://hgoebl.github.io/DavidWebb/

License: MIT License

Java 87.68% Shell 3.88% JavaScript 8.12% HTML 0.32%

davidwebb's People

Contributors

essobedo avatar hgoebl avatar pre avatar sandeepyohans 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

davidwebb's Issues

Crashes after update UI

I liked your library because ti's too simple. But it runs on the main thread and you can not update the UI after get the response.

handling multiple values with identical parameter name

http get requests support sending parameters with multiple values even though having identical keys.
in some cases, it is required by an external service api (in my case: solr's fq parameter can be called multiple times in a single http call in order to define filtering a query by various fields).

implementing the parameters list as a Map restricts the request to hold only one value for each parameter value.

Setting multiple headers

I'm having some trouble setting multiple headers using webb's HTTP library and I don't know if it's because I'm dense or I can't figure out how to cast types or something.

Here's my code:

Webb webb = Webb.create();
webb.setDefaultHeader( "User-Agent", "Java/8 by <APPLICATION_ID>" );
webb.setDefaultHeader( "Authorization", "bearer " + token );

JSONObject result = null;

try {
    result = webb
        .get( ABOUT_ME )
        .ensureSuccess()
        .asJsonObject()
        .getBody();
} catch ( WebbException ex ) {
    ...
}

I'm fairly certain that the second setDefaultHeader() is just overwriting the first statement because I found:

header(String name, Object value)
Set (or overwrite) >>a<< HTTP header value.

In the API docs, under Request. I tried just inserting .header( "header", "value") after get() and before ensureSuccess(), but then my IDE, NetBeans, said this symbol was not found.

Since header( String, String) is in the Request class, I just thought I could switch out the "Webb webb" declaration for "Request webb" as is shown here, but inserting either Request or Request<String> for the webb's variable type produced an error:

capture

capture2

Also, a little sidenote: In the header()'s Javadocs, there's a grammatical error. It should be "Set (or overwrite) an HTTP header value."

Upload File - How to ?

Hi !
I just discovered your project thanks to your post on stackExchange.
I want to upload a File to a server, and save it.

For now, I've got this code :

    Webb webb = Webb.create();
    Response<String> response = webb
            .post("http://..../test.php")
            .body(file)
            .connectTimeout(10 * 1000)
            .asString();

    if (response.isSuccess()) {
        String outcome = response.getBody();
        System.out.println(outcome);

    } else {
        System.out.println(response.getStatusCode());
        System.out.println(response.getResponseMessage());
        System.out.println(response.getErrorBody());
    }

My question is : How can I receive this file in the PHP Script ?
Do I need to look for something like $_FILES or $_POST ?

Oauth2

Goodnight.

I need to consume rest services that are protected by oauth2. Does this library help me to consume these services? Can I, with her, for example, make a post to my authentication server by sending the clientid and the secret in the authorization, and in the body the username, password, and type of grant type? to get a token, and things about these?

thank you

Dependency on org.json

I do not think this library should declare an explicit dependency on org.json since Android also includes org.json as part of its API, as can be seen from https://developer.android.com/reference/org/json/package-summary.html

By adding in a dependency on an external package implementing a similar API, the total size footprint for DavidWebb increases, and we run into potential class loading issues since the org.json package namespace is clobbered with multiple classes with the same name.

SSL error

Recently, an error is fired when calling a https request:

com.goebl.david.WebbException: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Is there a solution?

Would you please release an updated version for maven?

Hi,

I love your library and directly imported it in my maven project.
Currently it is 1.1.0 version from Feb, 2014.
I am trying to use the retry function but this version does not have this function.
Can you do another release when you have a chance?

Thanks!

An exception occurred when response content-encoding is UTF-8

Hello,
I am requesting to a url, and url returns Content-Encoding as UTF-8. Webb throws an exception with messsage: (WebbUtils -> wrapStream method)

unsupported content-encoding: UTF-8

I checked out the code, it's only supporting that content-encodings null, identity, gzip, deflate values.

How do I support UTF-8 encoding ?

How to get the output stream and pass in the body a writer

Hi,
I haven't been able to find any example of using Webb to send an http request with JSON in "streaming" mode.
I know it supports JSONObject, JSONArray, etc. but what if instead these classes we are using GSON to write an object as a streaming because JSONObject "DOM-like" serializing uses too much memory?

Usually I would get the output stream from the HttpURLConnection and then write there, but since Webb wraps HttpURLConnection, could you provide an example of sending some stream as the body?

Something like:
String urlSend = "http://myUrl";
Gson gson = new Gson();
MyCustomObject customObject = getCustomObjectFromSomewhere();
Webb webb = Webb.create();
//...and now how to stream and send it as body(streamed JSON) ?
OutputStream outputStream = new BufferedOutputStream(getOutputStreamFromSomewhere());
JsonWriter writer = new JsonWriter(new OutputStreamWriter(outputStream, "UTF-8"));
gson.toJson(customObject , MyCustomObject.class, writer);
webb.put(urlSend).ensureSuccess().body(writer); //something like that?

Any reference to more examples would be greatly appreciated.

Thank you!

Server response code 204

Using webb 1.3.
I'm doing a PUT request to a restful webservice using 2-way compression.
The server is returning code 204, which is successful request ("No content").
But the response is empty (as it should be);
WebbException: EOFException is being thrown because Webb is trying to decompress an empty response.

this is my code:
Response<Void> response = webb.put("descarga") .header(Webb.HDR_CONTENT_TYPE, Webb.APP_JSON) .body(byteArrayOutputStream.toByteArray()) .compress() .connectTimeout(Config.Webservice.getTimeout()) .retry(1, false) .ensureSuccess() .asVoid();

Middleware (hooks)

Hi there,
I'm using this project for my android project. And I wanted to implement a JWT token middleware which will automatically refresh a JWT if it was expired and then continue with the response. Coming across the readme, I found out that beforeSend and afterReceive are planned and are in Todo.

Coming from Golang/TypeScript world, I'd suggest something like this:

webb.AddMiddlware(jsonMiddleware)

Middleware implements an interface with method handle() which receives the original request and the next handler function

Now middleware can choose to either call the next or entirely skip, or maybe even modify the original request before continueing. Let me know if that makes sense 🙂

This one will totally resolve the necessity of the following todos:

  • decorator/interceptor beforeSend - provide hooks to manipulate request before send
  • decorator/interceptor afterReceive - provide hooks to manipulate raw response after receiving it

Let me know if you'll be willing to accept PRs :)

sample use

Would love to see a sample one activity project that works with android 4.0.4 - just get the contents of http://sel2in.com/prjs/php2/j.php?u=test and show it on a label. yep not even a web service :-) want to get some interns from a rural college ssism.org

Stream support

Hi,

Thank you for this library.
Have a question how to accomplish this with it.

I dont want to write to ByteArrayOutputStream and then send it.

URL url = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

ObjectOutputStream objOut = new ObjectOutputStream(new BufferedOutputStream(urlConnection.getOutputStream()));
objOut.writeObject("Hello");

objOut.flush();
objOut.close();

Allow to get the result as InputStream

Up to now, all results are loaded into memory as a byte array which makes it unusable to get big content such as big files for example. Moreover allowing to access to the result as InputStream allows the end user to use its own parser which is an open door to many new possibilities for the project.

No support for PATCH verb

To use the MailChimp 3.0 you have to use the method PATCH to do updates. Any reason this has not been implemented?

Gradle build warning

Hi,

In Android Studio, when gradle is built, shows these warnings:

Warning:Dependency org.json:json:20080701 is ignored for debug as it may be conflicting with the internal version provided by Android.
Warning:Dependency org.json:json:20080701 is ignored for release as it may be conflicting with the internal version provided by Android.

null ErrorStream when POST Request returns 401

When I do a POST Request with a JSON Body, where the server (Jboss) returns a 401 Error, the error stream is null.

When commenting out connection.setFixedLengthStreamingMode (WebbUtils.java) the error stream returns the server response.

Any Idea, how to fix this issue?

SocketTimeoutException on bad IP address

Great library.
However, it does not advertize that a SocketTimeoutException will be thrown on bad IP address. Here is the stack trace:

W/System.err﹕ com.goebl.david.WebbException: java.net.SocketTimeoutException: failed to connect to /10.20.120.57 (port 8080) after 10000ms
09-23 15:57:33.065 24791-24813/com.vmware.bsky W/System.err﹕ at com.goebl.david.Webb.execute(Webb.java:329)
09-23 15:57:33.065 24791-24813/com.vmware.bsky W/System.err﹕ at com.goebl.david.Request.asJsonObject(Request.java:257)
09-23 15:57:33.065 24791-24813/com.vmware.bsky W/System.err﹕ at com.vmware.bsky.ConfigCheckActivity$Async.doInBackground(ConfigCheckActivity.java:90)
09-23 15:57:33.066 24791-24813/com.vmware.bsky W/System.err﹕ at com.vmware.bsky.ConfigCheckActivity$Async.doInBackground(ConfigCheckActivity.java:71)
09-23 15:57:33.066 24791-24813/com.vmware.bsky W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:292)
09-23 15:57:33.066 24791-24813/com.vmware.bsky W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)

Send a file on request

Hello i add a video file on request

            Uri uri_video = Uri.parse(temp_usuario.getString("video_url"));
            File file = new File(getPath(uri_video));
            Webb webb = Webb.create();
            Response<String> response = webb
                    .post(getString(R.string.REST_URL) + "acciones_de_app/create_user.json")
                    .body(file)
                    .connectTimeout(10 * 3000)
                    .asString();

            if (response.isSuccess()) {
                String outcome = response.getBody();
                Log.e("a",outcome);


            } else {
                System.out.println(response.getStatusCode());
                System.out.println(response.getResponseMessage());
                System.out.println(response.getErrorBody());
            }

But when i recieved a body on action post

file = request.body.read
fp = File.open("/home/master/Escritorio/video_rest/video_mp.mp4", "wb")
fp.write(request.body.read)
fp.close

my file video_mp.mp4 created size a 0 byte

Canceling a request

I keep the connection open by holding the request on the server and not releasing it until something happens or the 30 seconds passes. However when I suddenly log out or an exception occurs I need something that will close the connection and cancel any outstanding requests. Does this function exist?

Error using put: VFY: unable to resolve virtual method setFixedLengthStreamingMode

Here's a chunk of the logcat with the VFY warning and the actual error.

01-20 11:30:06.724: W/dalvikvm(22051): VFY: unable to resolve virtual method 6870: Ljava/net/HttpURLConnection;.setFixedLengthStreamingMode (J)V
01-20 11:30:16.825: W/dalvikvm(22051): threadid=16: thread exiting with uncaught exception (group=0x4172c438)
01-20 11:30:16.915: E/AndroidRuntime(22051): FATAL EXCEPTION: IntentService[BeWell24Sync]
01-20 11:30:16.915: E/AndroidRuntime(22051): java.lang.NoSuchMethodError: java.net.HttpURLConnection.setFixedLengthStreamingMode
01-20 11:30:16.915: E/AndroidRuntime(22051): at com.goebl.david.WebbUtils.getPayloadAsBytesAndSetContentType(WebbUtils.java:237)
01-20 11:30:16.915: E/AndroidRuntime(22051): at com.goebl.david.Webb.execute(Webb.java:238)
01-20 11:30:16.915: E/AndroidRuntime(22051): at com.goebl.david.Request.asJsonObject(Request.java:217)
01-20 11:30:16.915: E/AndroidRuntime(22051): at edu.asu.snhp.bewell24.comms.SynchronizerService.syncTable(SynchronizerService.java:84)

Interestingly there's a new version of this method in API 19 with a different signature, but sadly the logcat doesn't show the full method signature. I have API 19 currently set as the target in my project's properties.

I'm a bit under the gun, so I wanted to post this early in case I'm doing something wrong that you can spot right away. I'll update this issue if I get any different results.

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.