I am new to Binance API and I'm having some difficulty to invoke Binance margin borrow API. I have referred their API documentation, But don't know how to invoke the margin borrow API through java. So, I would like to someone guide or share me an example code to invoke their margin API in java.
Thanks in advance
The request used by their website has the following curl structure:
curl --location --request GET 'https://www.binance.com/gateway-api/v1/public/margin/vip/spec/list-all' \
--header 'content-type: application/json'
In Java with apache http client, you can do it like this:
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet();
httpGet.setURI(new URI("https://www.binance.com/gateway-api/v1/public/margin/vip/spec/list-all"));
httpGet.setHeader("content-type", "application/json");
CloseableHttpResponse response = httpclient.execute(httpGet);
String responseJson = EntityUtils.toString(response.getEntity());
System.out.println(responseJson);
From what I could understand by a quick look at the docs, you will have to generate a HMAC SHA256 signature from your secretKey as the key and totalParams as the value for the HMAC operation and your API-key is passed into the Rest API via the X-MBX-APIKEY header.
String hmac = HMAC_SHA256("secret_key", "totalParams")
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("api uri here"))
.timeout(Duration.ofMinutes(1))
.header("X-MBX-APIKEY", "api-key here")
.POST(totalParamsHere)
.build()
Related
I am using the HttpClient and HttpRequest available on java.net.http. I have successfully sent some GET and POST requests, but I have no clue about how to send a PUT/POST request with multipart/form-data body:
HttpRequest dataRequest = HttpRequest.newBuilder()
.header("accept", "*/*")
.header("Content-Type", "multipart/form-data")
// .POST() ??
.uri(URI.create(DATA_URL)
.build();
The curl equivalent of this request would be something like:
curl -X PUT "https://www.example.com/data" -H "accept: */*" -H "Content-Type: multipart/form-data" -F "file=#audiofile.wav;type=audio/wav"
Should I use some kind of BodyPublishers in the POST() or PUT() method in order to achieve that? Any clue?
Multipart/form-data is not supported out of the box by the HttpClient API yet.
In JDK 16 there is a new HttpRequest.BodyPublishers.concat(BodyPublisher...) method that can be used to help build a request body built from the concatenation of bytes coming from heterogeneous sources.
But you would have to manually compose all the different parts, and handle base64 encoding when/if that's needed.
You could also try out methanol
This question already has answers here:
How do I POST JSON data with cURL?
(31 answers)
Closed 5 years ago.
Problem Statement
I am new to Spring/Rest Applications and I have data in an Object.
Now,I need to pass this data to an API.
Below is the sample curl Attached for a single record-
curl --request POST \
--url http://eventapi-dev.wynk.in/tv/events/v1/event \
--header 'cache-control: no-cache' \
--header 'content-type: application/json' \
--header 'postman-token: 67f73c14-791f-62fe-2b5a-179ba04f67ba' \
--data '{"name":"hotel california", "createdAt":1505727060471, "steamUrl":"https://www.youtube.com/watch?v=lHje9w7Ev4U"}'
The response I got after Hitting curl url in Terminal is Ok
Can I anyone guide me how to write the Code in Java.
You can using okhttp (https://github.com/square/okhttp) to call this api.
Example:
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\n\t\"name\":\"hotel california\", \n\t\"createdAt\":1505727060471, \n\t\"steamUrl\":\"https://www.youtube.com/watch?v=lHje9w7Ev4U\"\n}");
Request request = new Request.Builder()
.url("http://eventapi-dev.wynk.in/tv/events/v1/event")
.post(body)
.addHeader("content-type", "application/json")
.addHeader("cache-control", "no-cache")
.addHeader("postman-token", "08af0720-79cc-ff3d-2a7d-f208202e5ec0")
.build();
Response response = client.newCall(request).execute();
You have to use something similar as described here maily bu using HttpURLConnection & URL .
There you notice for post scenario that JSON data is passed as String
Then you can follow this question also to know few more answers using that API.
You can also use Apache HttpClient and browse examples on their site.
Apache HttpClient examples are here too.
I am not sure if I should just copy - paste relevant code samples from those websites to this answer ( for the sake of completeness ) but idea is very simply that you have to find an API that helps you in building and executing a REST request.
Another API is listed in answer by - Trần Đức Hùng and so we have numerous other Java APIs available in the market.
Url will be your end-point. It means you need to write a controller that can response your request, inside of your request there is some headers as you see. Those headers are for logging in and telling spring that you are sending json text. Also if you check your request it is "POST" so you also need to inform your controller method about this. It is good practice to catch all data with a model.
So your task should be like this.
Create controller that can response to your url.
Inform your controller method data is in Json format.
Inform your controller method it needs to wait for "POST" request.
Parse data to a model.
Let's try to do with code.
#RequestMapping(value = events.EVENT, method = RequestMethod.POST, consumes = {
MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE })
public Event eventAction(#RequestBody Event event){
}
In your case you need to define what is event. Class should be like this.
public class Quota implements Serializable{
private String name;
private Date createAt;
private String url;
// create getter setter
}
That is all now you are able to response this request. Inside of your controller method you can do your business logic.
I have a RESTful API that I can call by doing the following:
curl -H "Content-Type: application/json" -d '{"url":"http://www.example.com"}' http://www.example.com/post
In Java, when I print out the received request data from the cURL, I correctly get the following data:
Log: Data grabbed for POST data: {"url":"http://www.example.com/url"}
But when I send a POST request via Java using HttpClient/HttpPost, I am getting poorly formatted data that does not allow me to grab the key-value from the JSON.
Log: Data grabbed for POST data: url=http%3A%2F%2Fwww.example.com%2Furl
In Java, I am doing this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/post/");
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
BasicNameValuePair nvp1 = new BasicNameValuePair("url", "http://www.example.com/url);
nameValuePairs.add(nvp1);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpresponse = httpclient.execute(httppost);
How do I make it so that the request from Java is similar to cURL in terms of how the data is sent?
The data you present as coming from the Java client are URL-encoded. You appear to specifically request that by using a UrlEncodedFormEntity. It is not essential for the body of a POST request to be URL-encoded, so if you don't want that then use a more appropriate HttpEntity implementation.
In fact, if you want to convert generic name/value pairs to a JSON-format request body, as it seems you do, then you probably need either to use a JSON-specific HttpEntity implementation or to use a plainer implementation that allows you to format the body directly.
I would like to perform a post with binary data using Jersey Client.
The equivalent with curl would be:
curl -v --header "Content-Type:application/octet-stream" --data-binary "abc" http://example.com
I could not find how to do it in the official docs: http://jersey.java.net/documentation/latest/user-guide.html#client
Thanks.
I think you can invoke a POST request with Entity which encapsulates binary data like this:
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target("http://example.com/rest");
Response response = webTarget.request(MediaType.TEXT_PLAIN_TYPE)
.post(Entity.entity("abc", MediaType.APPLICATION_OCTET_STREAM));
Can someone help me figure out how to translate the following curl commands into Java syntax for use in an Android application?
The curl commands are:
curl -u username:password -H "Content-Type:application/vnd.org.snia.cdmi.container" http://localhost:8080/user
curl -u username:password -T /home/user1/a.jpg -H "Content-Type:image" http://localhost:8080/user/a.jpg
thanks
You can use Apache HttpClient in Android for performing HTTP posts.
HttpClient code snippet (untested)
public void postData(String url) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
// Set the headers (your -H options)
httpost.setHeader("Content-type", "application/json");
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("param1", "value1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
// Exception handling
}
}
Check the following link for the basic authentication part (your -u option)
http://dlinsin.blogspot.com/2009/08/http-basic-authentication-with-android.html
Check the following answer for your file upload (your -T option)
How to upload a file using Java HttpClient library working with PHP