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
Related
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()
I am using Apache http client, using cURL, the command would be:
curl -i -X POST --data-binary #data.csv -H "Content-Type:text/csv" "http://localhost:8080/"
What is the equivalent in Java(Apache Http Client) ? I tried the following:
HttpPost postRequest = new HttpPost("...");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
File file = new File("data.csv");
builder.addBinaryBody("upfile", file, ContentType.create("text/csv"), "data.csv");
HttpEntity entity = builder.build();
postRequest.setEntity(entity);
client.execute(postRequest);
That curl sends the file contents as the body (entity) directly, not in a multipart. Try
HttpPost post = new HttpPost(url);
post.setEntity(new FileEntity(new File(filename),ContentType.create("text/csv")));
... client.execute(post) ...
PS: curl -d/--data[-*] already uses POST, you don't need -X.
I have a cURL command:
curl -d '{"mobile_number":"09178005343", "pin":"1111"}' -H "Content:Type: application/json" -H "X-Gateway-Auth:authentication" -X POST https://localhost:9999/api/traces/%2f/login
I need to create an HTTP Request in Java API which will do the same thing. I don't have any idea regarding this. Thank you in advance for those who will take time to respond.
There are multiple ways to do it. Firstly, since you want to send a JSON object, you might want to use a JSON library, for example, Google's gson. But to make it easy you can just send the request as a String. Here is a sample code that sends your JSON to your URL.
HttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("https://localhost:9999/api/traces/%2f/login");
StringEntity params =new StringEntity("{\"mobile_number\":\"09178005343\", \"pin\":\"1111\"");
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
//Do what you want with the response
}catch (Exception ex) {
//If exception occurs handle it
} finally {
//Close the connection
}
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.
This my android code I used to send to my php file in website. also modified android manifest file.
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(7);
nameValuePairs.add(new BasicNameValuePair("number", "5556"));
nameValuePairs.add(new BasicNameValuePair("password",password));
nameValuePairs.add(new BasicNameValuePair("token",token));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://futuretime.in/post.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
This is my php script for receiving data from android.
But my problem is when I printed data in php it is not showing any value.
<?php
$number= $_POST['number'];
$password = $_POST['password'];
$token = $_POST['token'];
echo $number;
?>
you can try use Ion https://github.com/koush/ion ,is a great library for make http request.
is a simple example .check the project site for more examples and wiki.
Ion.with(getContext(), "https://koush.clockworkmod.com/test/echo")
.setBodyParameter("goop", "noop")
.setBodyParameter("foo", "bar")
.asString()
.setCallback(...)