EzDevInfo.com

clj-http

An idiomatic clojure http client wrapping the apache client. Offically supported version. clj-http 2.0.0 - Clojars

clj-http/get url {:as :json} doesn't work in script but in REPL

I'm experimenting with Clojure and Leiningen. I was successful in executing to following line in the REPL:

(print (:body (client/get "https://coinbase.com/api/v1/prices/spot_rate?currency=CAD" {:as :json}))

I created a project with lein new http. When I run the following lines witn lein run then the coercion to JSON doesn't work. It simply prints a correct JSON string.

(ns http.core
  (:require [clj-http.client :as client])
  (:use clojure.pprint))

(defn -main
  []
  (print
    (:body
      (client/get "https://coinbase.com/api/v1/prices/spot_rate?currency=CAD" {:as :json}))

the output of the script is

{"amount":"306.89","currency":"CAD"}

Any idea what's wrong?


Source: (StackOverflow)

handle uncaught_exception in clojure

I have a clojure endpoint in my project which basically updates a document in couchdb.

(^{PUT true
       Path "/{id}"
       Produces ["application/json"]
       Consumes ["application/json"]
       ApiOperation {:value "Update" :notes ""}
      }
     method_name [this
                     ^{PathParam "id"} id
                     body]
     (require 'com.xx.x.xx.xx.xx-response)
     (let [doc (json/read-json body)]
       (if-let [valid-doc (validate doc)]
         (try+
          (->>
           (assoc valid-doc :modificationDate (Utilities/getCurrentDate))
           (couch/update-document dbs/xx-db)
           (core/ok-response))
          (catch java.io.IOException ex
              (log/error "line num 197")
           )
          (catch java.lang.Exception ex
            (log/error "line num 200")))
)))

This endpoint throws a 500 uncaught exception when there is a document conflict along with the cause of the exception and this gets logged in the log files. The trace-redirects has sensitive information. I added a catch block to handle this exception [clojure.lang.ExceptionInfo]. It didn't work.

How do I handle this? Is there a way to remove trace-redirects?

Request exception uncaught_exception Status 500 Message An exception was thrown that was not handled by the application or a provider.
clojure.lang.ExceptionInfo: throw+: {:trace-redirects ["https://abc123xyz-dev:separate settled first deal@abc123xyz-dev.cloudant.com/1111"], :request-time 3899, :request {:path "/sss", :protocol "https", :scheme :https, :data nil, :http-url "https://abc123xyz-dev.cloudant.com/1111", :conn-timeout 6000, :host "abc123xyz-dev.cloudant.com", :follow-redirects true, :request-method :post, :query-string nil, :save-request? true, :anchor nil, :http-req #<HttpPost POST https://abc123xyz-dev.cloudant.com/1111 HTTP/1.1>, :as :json, :uri "/1111", :port -1, :username "abc123xyz-dev", :data-length nil, :server-name "abc123xyz-dev.cloudant.com", :headers {"authorization" "Basic bGl2ZW1vY2hhLWRldjpzZXXBhcmF0ZSBzZXR0bGVkI1ZpcnN0IGRlY111Ww=", "accept-encoding" "gzip, deflate", "content-type" "application/json", "user-agent" "com.ashafa.clutch/0.3.0", "accept" "*/*"}, :socket-timeout 6000, :body-type nil, :server-port nil, :query nil, :password "90t!@"}, :status 400, :headers {"server" "CouchDB/1.0.2 (Erlang OTP/R14B)", "strict-transport-security" "max-age=31536000", "x-couch-request-id" "119df05d59", "content-type" "text/plain;charset=utf-8", "date" "Thu, 18 Jun 2015 17:46:08 GMT", "cache-control" "must-revalidate", "x-content-type-options" "nosniff;", "content-length" "54", "connection" "close"}, :body "{\"error\":\"bad_request\",\"reason\":\"invalid UTF-8 JSON\"}\n"}

Update: Apologies. This error occurs even when a valid json is posted for update. Sorry if that was misleading.

  • Thanks

Source: (StackOverflow)

Advertisements

Unable to resolve clj-http

I want to use clj-http, so I created a project with lein with these dependencies in project.clj:

(defproject app "0.1.0-SNAPSHOT"
:description "FIXME: write description"
:main app.core
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
          :url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.7.0"]
            [clj-http "2.0.0"]])

src/app/core.clj:

(ns app.core
  (:require [clj-http.client :as client]))

(println client)

(defn -main
  [& args])

when I use lein clean && lein deps && lein run, I get an error message:

Exception in thread "main" java.lang.RuntimeException: Unable to resolve symbol: client in this context, compiling:(app/core.clj:4:1)
    at clojure.lang.Compiler.analyze(Compiler.java:6543)
    at clojure.lang.Compiler.analyze(Compiler.java:6485)
    at clojure.lang.Compiler$InvokeExpr.parse(Compiler.java:3791)
    at clojure.lang.Compiler.analyzeSeq(Compiler.java:6725)
    at clojure.lang.Compiler.analyze(Compiler.java:6524)
    at clojure.lang.Compiler.analyze(Compiler.java:6485)

lein version output:

Leiningen 2.5.3 on Java 1.8.0_45 Java HotSpot(TM) 64-Bit Server VM

Did I make something wrong? I followed exactly the clj-http documentation.

Thank you.


Source: (StackOverflow)

clojure https connect using TLS 1.2 protocol

Trying connect to https server (https://3dsecure.kkb.kz) using TLS 1.2.

(defn- http-request-clojure [xml req-type]
  (let [url-info  (url-map  req-type)
   (prepare-response (.toString (:body (client/get
                                        (str (:url url-info) "?"
                                             (and (:name url-info)
                                                  (str (:name url-info) "="))
                                             (URLEncoder/encode xml))
                                        {:insecure? true
                                         :socket-timeout 10000
                                         :conn-timeout 10000}))))))

Got error "javax.net.ssl.SSLException: Received fatal alert: protocol_version"

openssl 1.0.1g , java 7.

Any ideas what goes wrong?


Source: (StackOverflow)

How to wrap oAuth headers in clj-http?

I'm trying to post a twitter status update with clojure... but this probably really is a question about oAuth headers, and using it through the wonderful clj-http library.

I've used clj-http before for basic-auth and other type of headers and it was fairly straightforward. The Authorization: Bearer ... was a bit confusing but I got there in the end.

For twitter though, I am supposed to pass a lot of variables in Authorization and I am not quite sure how I'd go about doing that. Here's the curl command, according to twitter, that I'll need to post the tweet:

curl --request 'POST' 'https://api.twitter.com/1.1/statuses/update.json' 
     --data 'status=this+is+sparta' 
     --header 'Authorization: OAuth oauth_consumer_key="xxxxx",
                              oauth_nonce="xxxxx", 
                              oauth_signature="xxxxx", 
                              oauth_token="xxxxx", oauth_version="1.0"' 
     --verbose

So I am not sure how I would append all the oAuth... things in the header. trying with (str ..) isn't really working out. Here's what I've got so far:

(client/post "https://api.twitter.com/1.1/statuses/update.json")
             {:headers {:Authorization (str "OAuth oauth_consumer_key='xxxxx', oauth_nonce='xxxxx', oauth_signature='xxxxx', oauth_token='xxxxx', oauth_version='1.0'" )}
              :form-params {:status "This is sparta"})

This returns 403. permission error when I try.

Any ideas on how I'd construct that query?

ps: I do have the oAuth token and token_secret for the account... but I notice the token_secret value isn't being passed? and what does oauth_nonce for? I'm for now passing the value that twitter gave me for curl... looking around it seems that it is just a random value so not that fussed about it.


Source: (StackOverflow)