What is the Java equivalent for the following in curl? -
curl https://view-api.box.com/1/documents \ -h "authorization: token your_api_key" \ -h "content-type: application/json" \ -d '{"url": "https://cloud.box.com/shared/static/4qhegqxubg8ox0uj5ys8.pdf"}' \ -x post how accomodate url?
this tried far.
final string url = "https://view-api.box.com/1/documents"; @suppresswarnings("resource") final httpclient client = httpclientbuilder.create().build(); final httppost post = new httppost(url); post.setheader("authorization", "token: token_id"); post.setheader("content-type", "application/json"); final list<namevaluepair> urlparameters = new arraylist<namevaluepair>(); urlparameters.add(new basicnamevaluepair("url", "https://cloud.box.com/shared/static/4qhegqxubg8ox0uj5ys8.pdf")); post.setentity(new urlencodedformentity(urlparameters)); final httpresponse response = client.execute(post); system.out.println("response code : " + response.getstatusline().getstatuscode()); final bufferedreader rd = new bufferedreader(new inputstreamreader(response.getentity().getcontent())); final stringbuffer result = new stringbuffer(); string line = ""; while ((line = rd.readline()) != null) { result.append(line); } }
you have ok except entity, you're sending in curl not content of html form json object.
first take off part (don't send data if application/x-www-form-urlencoded):
// comment out / delete code: final list<namevaluepair> urlparameters = new arraylist<namevaluepair>(); urlparameters.add(new basicnamevaluepair("url", "https://cloud.box.com/shared/static/4qhegqxubg8ox0uj5ys8.pdf")); post.setentity(new urlencodedformentity(urlparameters)); and add body in way:
basichttpentity entity = new basichttpentity(); inputstream body = new bytearrayinputstream( "{\"url\": \"https://cloud.box.com/shared/static/4qhegqxubg8ox0uj5ys8.pdf\"}".getbytes()); entity.setcontent(body); post.setentity(entity); i'm assuming json string have chars between 0x20 , 0x7f, if use other characters (like Ñ) need transform data bytearray using encoding utf-8 (the standard encoding used in json data) in way:
basichttpentity entity = new basichttpentity(); string mydata = "{\"url\": \"https://cloud.box.com/shared/static/4qhegqxubg8ox0uj5ys8.pdf\"}"; bytearrayoutputstream rawbytes = new bytearrayoutputstream(); outputstreamwriter writer = new outputstreamwriter(rawbytes, charset.forname("utf-8")); writer.append(mydata); inputstream body = new bytearrayinputstream(rawbytes.tobytearray()); entity.setcontent(body); post.setentity(entity);
Comments
Post a Comment