Using Curl in Android

Using cURL in Android

I'm on a similar quest! I'm working on an app right now that requires cURL and just tonight in my search I came across your post here, and what I believe to be the answer:

http://thesoftwarerogue.blogspot.com/2010/05/porting-of-libcurl-to-android-os-using.html

Unlike the link you referenced, there are several follow-up comments from other people who claim to have success also following the instructions. If you manage to get it compiled before me, and wouldn't mind sending me the library, post a follow up here! (I'm pretty new to stack overflow so I don't know if you can pm.) Hope this works out for both of us!

How to use curl in Android?

You can use httpget method with username, password credentials.
Here i show you the method.

public static String getRequest() {
StringBuffer stringBuffer = new StringBuffer("");
BufferedReader bufferedReader = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet();

URI uri = new URI("http://10.1.1.83/outlet?2=OFF");
httpGet.setURI(uri);
httpGet.addHeader(BasicScheme.authenticate(
new UsernamePasswordCredentials("admin", "1234"),
HTTP.UTF_8, false));

HttpResponse httpResponse = httpClient.execute(httpGet);
InputStream inputStream = httpResponse.getEntity().getContent();
bufferedReader = new BufferedReader(new InputStreamReader(
inputStream));

String readLine = bufferedReader.readLine();
while (readLine != null) {
stringBuffer.append(readLine);
stringBuffer.append("\n");
readLine = bufferedReader.readLine();
}
} catch (Exception e) {
// TODO: handle exception
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
// TODO: handle exception
}
}
}
return stringBuffer.toString();
}

use this code in your script, it'll work.

Using cURL commands in Android

Use JSONObject instead of just a List of name/value pairs.

Use a StringEntity instead of a UrlEncodedFormEntity.

Build a JsonObject wrapping your KV strings and then use a 'writer' to dump the Object to a string in the form of a StringEntity on the POST request in httpclient.

some relevant code using "Jackson" for the JsonObj implementation and httpclientandroid.

      ObjectNode rootOb = new ObjectMapper().createObjectNode();
rootOb.put("username",user );
...
StringWriter writer = new StringWriter();
try {
new ObjectMapper().writeValue(writer, rootOb);
} catch (JsonGenerationException e) {

}
String poststr=writer.toString();
new HttpConnection(handler4).post(url, poststr);
...
httpPost.setEntity(new StringEntity(poststr));

testing with curl -VERBOSE first then just reimplement exactly the curl in android is a very good technique as long as you are able to turn on LOGGER in the android httpclient that gives you HEADER / WIRE level logging when you need to verify that your android does EXACT or almost exact what your Curl client was doing.

example below of a curl expression followed by Android logs (WIRE/HEADERS) showing android analogs of the same stuff you sent using Curl.

curl -v -X POST \
-H "X-Parse-Application-Id: LAbR" \
-H "X-Parse-REST-API-Key: ke" \
-H "Content-Type: application/json" \
-d '{"score":1337,"playerName":"Sean Plott","cheatMode":false}' \
https://api.parse.com/1/classes/GameScore

D/ch.boye.httpclientandroidlib.wire(18636): >> "POST /1/files/audio HTTP/1.1[\r][\n]"
D/ch.boye.httpclientandroidlib.wire(18636): >> "X-Parse-Application-Id: LAbR[\r][\n]"
D/ch.boye.httpclientandroidlib.wire(18636): >> "X-Parse-REST-API-Key: kuI9[\r][\n]"
D/ch.boye.httpclientandroidlib.wire(18636): >> "Content-Type: audio/*[\r][\n]"
D/ch.boye.httpclientandroidlib.wire(18636): >> "Content-Length: 12074[\r][\n]"
D/ch.boye.httpclientandroidlib.wire(18636): >> "Host: api.parse.com[\r][\n]"
D/ch.boye.httpclientandroidlib.wire(18636): >> "Connection: Keep-Alive[\r][\n]"
D/ch.boye.httpclientandroidlib.wire(18636): >> "[\r][\n]"
D/ch.boye.httpclientandroidlib.wire(18636): >> "--"
D/ch.boye.httpclientandroidlib.wire(18636): >> "cVxX6b-jxQnxFCczaKHLNZ_Hq8HI9AEW219GW3w"
D/ch.boye.httpclientandroidlib.wire(18636): >> "[\r][\n]"
D/ch.boye.httpclientandroidlib.wire(18636): >> "Content-Disposition"
D/ch.boye.httpclientandroidlib.wire(18636): >> ": "
D/ch.boye.httpclientandroidlib.wire(18636): >> "form-data; name="bin"; filename="myfile.3gp""
D/ch.boye.httpclientandroidlib.wire(18636): >> "[\r][\n]"
D/ch.boye.httpclientandroidlib.wire(18636): >> "Content-Type"
D/ch.boye.httpclientandroidlib.wire(18636): >> ": "
D/ch.boye.httpclientandroidlib.wire(18636): >> "application/octet-stream"
D/ch.boye.httpclientandroidlib.wire(18636): >> "[\r][\n]"
D/ch.boye.httpclientandroidlib.wire(18636): >> "[\r][\n]"

D/ch.boye.httpclientandroidlib.headers(18636): >> POST /1/files/audio HTTP/1.1
D/ch.boye.httpclientandroidlib.headers(18636): >> X-Parse-Application-Id: LAbR
D/ch.boye.httpclientandroidlib.headers(18636): >> X-Parse-REST-API-Key: kuI9
D/ch.boye.httpclientandroidlib.headers(18636): >> Content-Type: audio/*
D/ch.boye.httpclientandroidlib.headers(18636): >> Content-Length: 12074
D/ch.boye.httpclientandroidlib.headers(18636): >> Host: api.parse.com
D/ch.boye.httpclientandroidlib.headers(18636): >> Connection: Keep-Alive

When you get used to turning on/off your android logs, anything you do in Curl for connection tests, you can then just implement in android httpclient and it will work as long as you put basically same headers, mimetype, post body (JsonAsString) in your android.

CURL in android

Let's assume that you want to do the following request:

curl -u user:password http://sample.campfirenow.com/rooms.xml

In Android you would do as follow.

public static String getRequest() {
StringBuffer stringBuffer = new StringBuffer("");
BufferedReader bufferedReader = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet();

URI uri = new URI("http://sample.campfirenow.com/rooms.xml");
httpGet.setURI(uri);
httpGet.addHeader(BasicScheme.authenticate(
new UsernamePasswordCredentials("user", "password"),
HTTP.UTF_8, false));

HttpResponse httpResponse = httpClient.execute(httpGet);
InputStream inputStream = httpResponse.getEntity().getContent();
bufferedReader = new BufferedReader(new InputStreamReader(
inputStream));

String readLine = bufferedReader.readLine();
while (readLine != null) {
stringBuffer.append(readLine);
stringBuffer.append("\n");
readLine = bufferedReader.readLine();
}
} catch (Exception e) {
// TODO: handle exception
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
// TODO: handle exception
}
}
}
return stringBuffer.toString();
}

You can change HttpGet to HttpPost / HttpPut / HttpDelete depending on what you need to access.

Cheers.

How can I run cUrl calls in Android?

While it is possible to run that command directly from Java, you should not do that. Each phone is different and it is very much possible that some Android phones might not have curl installed on them.

You can use libraries such as Apache or OkHttp to do so. Here is a snippet that works with OkHttp 3.2.0:

//file is your opened file and url is the server url
OkHttpClient client = new OkHttpClient.Builder().build();
RequestBody formBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse("text/plain"), file))
.build();
Request request = new Request.Builder().url(url).post(formBody).build();
Response response = client.newCall(request).execute();

Make android login form using Curl

This is just an example... the exact coding for your particular login system may be different.

The server login file PHP would be similar to this:

if (isset($_POST['username']) && $_POST['username'] != '') {
$loginPassword = $_POST['password'];
$username = $_POST['username'];
$sql = "SELECT `id`, `username`, `email`, `password`, `key` FROM `TABLE_NAME` WHERE `username`=:username";
$LoginRS_query = $conn->prepare($sql);
$LoginRS_query->bindValue(':username', $username, PDO::PARAM_STR);
$LoginRS_query->execute();
$LoginRS = $LoginRS_query->fetch(PDO::FETCH_ASSOC);
$totalRows = $LoginRS_query->rowCount();

if($totalRows > 0) {
$db_key = $LoginRS['key'];
$peppered = hash_hmac("sha256", $loginPassword, $db_key);
$db_pwd = $LoginRS['password'];
if(password_verify($peppered, $db_pwd)) {
$loginFoundUser = 'true';
} else {
$loginFoundUser = 'false';
}
}

if($loginFoundUser == 'true') {
$loginID = $LoginRS['id'];
$loginUserName = $LoginRS['username'];

$LoginRS_query->closeCursor();

echo "success";

$response = array('id' => $loginID, 'username' => $loginUserName);
echo json_encode($response);
} else {
$LoginRS_query->closeCursor();
echo "no user found";
}
} else {
echo "access failed";
}

Then in your activity file inside sendLogin() ...

public void onResponse(String response) {
if (response.contains("success")) {
String res = response.substring(response.indexOf("{"));
try {
JSONObject jsonObject = new JSONObject(res);
final String loginID = jsonObject.getString("id");
final String loginUser = jsonObject.getString("username");

Intent intent = new Intent(MainActivity.this, menu.class);
intent.putExtra("id", loginID); // added this line
intent.putExtra("username", loginUser); // added this line
startActivity(intent);
finish();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Login Error " + e, Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(getApplicationContext(), "Username & Password Salah", Toast.LENGTH_LONG).show();
}

The intent.putExtra is only needed if you will need your username or ID elsewhere to perform other tasks

How to write / convert CURL for Android java

It's easy to do with Jsoup:

    // CREATE CONNECTION
Connection conn=Jsoup.connect("URL_GOES_HERE");

// ADD POST/FORM DATA
conn.data("KEY", "VALUE");

// ADD HEADERS HERE
conn.header("KEY", "VALUE");

// SET METHOD AS POST
conn.method(Connection.Method.POST);

// ACCEPT RESPONDING CONTENT TYPE
conn.ignoreContentType(true);

try
{
// GET RESPONSE
String response = conn.execute().body();

// USE RESPONSE HERE
// CREATE JSON OBJECT OR ANYTHING...
} catch(HttpStatusException e)
{
int status = e.getStatusCode();
// HANDLE HTTP ERROR HERE
} catch (IOException e)
{
// HANDLE IO ERRORS HERE
}

Ps: I guess you are confused with Header and Post Data. The key etc (Credentials) must be used as Post Data and Content Type etc as Header.



Related Topics



Leave a reply



Submit