How to send SMS using Twilio in my android application? - android

In my android application I have created one button, when I had pressed on the button I want to send message.So for that I have created one java class and written twilio code.
final TwilioRestClient client = new TwilioRestClient(
ACCOUNT_SID, AUTH_TOKEN);
// Get the main account (The one we used to authenticate the
// client)
final Account mainAccount = client.getAccount();
final SmsFactory messageFactory = mainAccount.getSmsFactory();
final Map<String, String> messageParams = new HashMap<String, String>();
messageParams.put("To", "+912342423423");
messageParams.put("From", "+132432432434");
messageParams.put("Body", "This is my message");
try {
messageFactory.create(messageParams);
} catch (TwilioRestException e) {
e.printStackTrace();
}
when I am using the above code it showing some error like java.lang.NoSuchMethodError: org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager
I have added only one jar file in lib folder as " twilio-java-sdk-3.3.10-jar-with-dependencies.jar ".
please tell me what can I do?

I have used HttpPost method to send sms in that i have passed my url with base authentication here is my code
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"https://api.twilio.com/2010-04-01/Accounts/{ACCOUNT_SID}/SMS/Messages");
String base64EncodedCredentials = "Basic "
+ Base64.encodeToString(
(ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(),
Base64.NO_WRAP);
httppost.setHeader("Authorization",
base64EncodedCredentials);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("From",
"+123424353534"));
nameValuePairs.add(new BasicNameValuePair("To",
"+914342423434"));
nameValuePairs.add(new BasicNameValuePair("Body",
"Welcome to Twilio"));
httppost.setEntity(new UrlEncodedFormEntity(
nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
System.out.println("Entity post is: "
+ EntityUtils.toString(entity));
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
It is working well.

This solution with Retrofit
public static final String ACCOUNT_SID = "accountSId";
public static final String AUTH_TOKEN = "authToken";
private void sendMessage() {
String body = "Hello test";
String from = "+...";
String to = "+...";
String base64EncodedCredentials = "Basic " + Base64.encodeToString(
(ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(), Base64.NO_WRAP
);
Map<String, String> data = new HashMap<>();
data.put("From", from);
data.put("To", to);
data.put("Body", body);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.twilio.com/2010-04-01/")
.build();
TwilioApi api = retrofit.create(TwilioApi.class);
api.sendMessage(ACCOUNT_SID, base64EncodedCredentials, data).enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) Log.d("TAG", "onResponse->success");
else Log.d("TAG", "onResponse->failure");
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("TAG", "onFailure");
}
});
}
interface TwilioApi {
#FormUrlEncoded
#POST("Accounts/{ACCOUNT_SID}/SMS/Messages")
Call<ResponseBody> sendMessage(
#Path("ACCOUNT_SID") String accountSId,
#Header("Authorization") String signature,
#FieldMap Map<String, String> metadata
);
}
Dependencies for build.gradle
compile 'com.squareup.retrofit2:retrofit:2.1.0'

My method, using OkHttp:
1. Prerequisites
Gradle:
dependencies {
compile 'com.squareup.okhttp3:okhttp:3.4.1'
}
Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
Permission in activity:
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.setThreadPolicy( new StrictMode.ThreadPolicy.Builder().permitAll().build() );
}
2. Code
private void sendSms(String toPhoneNumber, String message){
OkHttpClient client = new OkHttpClient();
String url = "https://api.twilio.com/2010-04-01/Accounts/"+ACCOUNT_SID+"/SMS/Messages";
String base64EncodedCredentials = "Basic " + Base64.encodeToString((ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(), Base64.NO_WRAP);
RequestBody body = new FormBody.Builder()
.add("From", fromPhoneNumber)
.add("To", toPhoneNumber)
.add("Body", message)
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.header("Authorization", base64EncodedCredentials)
.build();
try {
Response response = client.newCall(request).execute();
Log.d(TAG, "sendSms: "+ response.body().string());
} catch (IOException e) { e.printStackTrace(); }
}
I used Allu code for generathing authorization in header

Twilio Java SDK has third party dependencies without them it is not going to work. The dependencies are:
1. Httpcore
2. Httpclient
3. Commons lang
4. Json simple
5. Jackson
Not quite sure if you need them all, but at least now you are missing httpcore

You should use the BasicPhone project of Twilio SDK. I've tried this to call and now I can call too. This project has all the methods and functions that you need to call and to send SMS. First of all, you need a PHP web service to get capability token and pass that PHP script into your app.

This is how I solved my need.
public class TwilioAsyncTask extends AsyncTask {
Context context;
ProgressDialog progressDialog;
public TwilioAsyncTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... strings) {
//
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"https://api.twilio.com/2010-04-01/Accounts/AC_yourACCOUNT_SID_9b/SMS/Messages");
String base64EncodedCredentials = "Basic "
+ Base64.encodeToString(
(ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(),
Base64.NO_WRAP);
httppost.setHeader("Authorization",
base64EncodedCredentials);
try {
int randomPIN = (int) (Math.random() * 9000) + 1000;
String randomVeriValue = "" + randomPIN;
// these are for control in other anctivity used sharepreference
editorTwilio.putString("twilio_veri_no", randomVeriValue);
editorTwilio.commit();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("From",
"+148******")); // what number they gave you
nameValuePairs.add(new BasicNameValuePair("To",
"+90" + phoneNo)); // your phone or our customers
nameValuePairs.add(new BasicNameValuePair("Body",
"Your verification number is : " + randomVeriValue));
httppost.setEntity(new UrlEncodedFormEntity(
nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
System.out.println("Entity post is: "
+ EntityUtils.toString(entity));
// Util.showMessage(mParentAct, "Welcome");
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
//
return "Executed";
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
//progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(context, "", " Wait for ");
}
#Override
protected void onProgressUpdate(String... text) {
// Things to be done while execution of long running operation is in
// progress. For example updating ProgessDialog
}
}
And call your Task
TwilioAsyncTask task = new TwilioAsyncTask(CountryAndPhone.this);
task.execute();

Related

basic authentication server not working on jellybeans and kitkat

I am using basic authentic for http connection in app. App is working finr correctly on devices with higher versions. I have also searched for solution and It did not worked for me.
Here is my code for connection
public static String executeHttpPost(Activity activity, String url,
ArrayList<NameValuePair> postParameters) {
String value = "{\"status\":false,\"message\":\"Server Timeout, connection problem, Please try later\"}";
try {
final String basicAuth = "Basic " + Base64.encodeToString(
("abc" + ":" + "abcd").getBytes(), Base64.NO_WRAP);
networkConnection = new NetworkConnection();
if (networkConnection.isOnline(activity)) {
postParameters.add(new BasicNameValuePair("device_type","android"));
HttpClient client = getNewHttpClient();
HttpPost post = new HttpPost(url);
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParameters, "UTF-8");
post.setEntity(entity);
post.setHeader("Authorization",basicAuth);
post.setHeader("some-parameter","abc");
org.apache.http.HttpResponse result = client.execute(post);
value = EntityUtils.toString(result.getEntity());
}catch (Exception e){}
String s = "";
for (NameValuePair param : postParameters) {
s = s + param.getName() + " = " + param.getValue() + " ";
}
if (value != null) {
WebUrl.ShowLog("From " + url +" parameters "+s
+ " Response : " + value.trim());
return value.trim();
} else {
return value;
}
} else {
activity.startActivity(new Intent(activity, NoInternet.class));
activity.finish();
return "{\"status\":false,\"message\":\"\"}";
}
} catch (Exception e) {
e.printStackTrace();
return value;
}
}
This is the only link I found, but it didn't work for me
You should use Google Volley for the connections with the server. There are many ways to get connect, but using "Google Volley" in Android development is so simple, reliable and as it comes as a dependency it gets bundled with your package. So never worry about compatibility over many old and many current and upcoming Android versions.
I have used it 5 years ago and it was working on all major platforms. Very easy to program.
Have a look:
final TextView mTextView = (TextView) findViewById(R.id.text);
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
How simple is it.

Send parameters via POST method in Android

I am developing an Android App
The below mentioned is the link .
"http://example.com.in/ai/abc?var="+var
where var is a variable where result has come.I want to post the data available in the var along with the link . I am new to android so I want to know How to do POST method in Android App.
You should do something like this:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
You can use Android Volley Library to post your data to your php script.Here is the example of Volley Request
//Declare the URL you want to send
public static String YOUR_URL = "http://example.com.in/ai/abc?var=";
private void postDataToServer() {
//volley request
//here you can choose your method,GET/POST,in this case is Post
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.POST,
YOUR_URL , null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//if send data success do something here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//if having error to make request to server do something here
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//send your parameter here
Map<String, String> parameters = new HashMap<>();
parameters.put("yourVariable", "var");
return parameters;
}
//adding header to authenticate
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonReq);
}
You can look at this tutorial to see how to post data from Android and get the data in your php script.

AsyncHttpClient POST params become null on server

I am writing method to insert a new record to DB from android.
On client (android studio), I use AsyncHttpClient POST:
JSONObject params = new JSONObject();
try {
params.put("idOrd", idOrd);
params.put("idLan", aIdLan);
params.put("dbIP", dbIP);
params.put("dbName", dbName);
params.put("dbUsername", dbUsername);
params.put("dbPassword", Utility.dbEncrypt(dbPassword));
wsEditMaster(params);
} catch (JSONException | UnsupportedEncodingException e) {
e.printStackTrace();
}
public void wsEditMaster(final JSONObject params) throws UnsupportedEncodingException {
ByteArrayEntity entity = new ByteArrayEntity(params.toString().getBytes("UTF-8"));
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"));
client.post(this, "http://" + serverIP + "/DHD/general/editorder", entity, "application/x-www-form-urlencoded", new AsyncHttpResponseHandler() {
And on server (eclipse):
// HTTP Post Method
#POST
// Path: http://localhost/<appln-folder-name>/general/editorder
#Path("/editorder")
// Produces JSON as response
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
// Query parameters are parameters:
public String editOrder(#FormParam("idOrd") String idOrd,
#FormParam("idLan") String idLan, #FormParam("dbIP") String dbIP,
#FormParam("dbName") String dbName,
#FormParam("dbUsername") String dbUsername,
#FormParam("dbPassword") String dbPassword) throws Exception {
String response = "";
if (DBConnection.editOrder(idOrd, idLan, dbIP, dbName, dbUsername, dbPassword)) {
response = Utility.constructJSON("editOrder", true);
} else {
response = Utility.constructJSON("editOrder", false,
"Cannot insert to database!");
}
return response;
}
Everything works fine when I use GET, but when I use POST, all params became null in "editOrder" function.
Please help, thank you.
OK, I solved my problem. Simply, use RequestParams instead of JSONObject:
public void wsEditMaster(final RequestParams params) {
client.post("http://" + serverIP + "/DHD/general/editorder", params, new AsyncHttpResponseHandler() {

Post JsonObject use Volley

I am using HttpPost to post data to a backend server, and it work well with this code below :
public void postData() {
String url = Configs.URL_OWS;
String odmName = Configs.ODM;
String keymd5 = getKeyMD5();
JSONObject jsonObject = new JSONObject();
jsonObject.put("model", model);
jsonObject.put("imei", imei1);
jsonObject.put("imei2", imei2);
jsonObject.put("build", buildVersion);
if (CommonUtils.isNetworkConnected(mContext)) {
// Create a new HttpClient and Post Header
Handler handler = new Handler(Looper.getMainLooper());
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, Configs.TIME_OUT);
HttpConnectionParams.setSoTimeout(myParams, Configs.TIME_OUT);
HttpClient httpclient = new DefaultHttpClient(myParams);
try {
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
httppost.addHeader("Authorization", odmName + ":" + keymd5);
// httppost.addHeader("POST", "/api/ows HTTP/1.1");
StringEntity se = new StringEntity(jsonObject.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String result = EntityUtils.toString(response.getEntity());
JSONObject jsonResponse = new JSONObject(result);
String status = jsonResponse.optString("status");
if (status.equals(Configs.RESPONSE_OK)) { // response 200, send successfull
Log.i(Configs.APP_NAME + " " + TAG, "Send data successful");
} else {
Log.i(Configs.APP_NAME + " " + TAG, "Send data failed:");
}
} catch (final ClientProtocolException e) {
Log.i(Configs.APP_NAME + " " + TAG, "ClientProtocolException " + e.getMessage());
} catch (final IOException e) {
Log.i(Configs.APP_NAME + " " + TAG, "IOException " + e.getMessage());
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.i(Configs.APP_NAME + " " + TAG, "Network not connected ");
}
}
I switched to use Volley instead HttpPost but server always return error , the code for Volley method :
public void postDataByVolley() {
String url = Configs.URL_OWS;
String odmName = Configs.ODM;
final String keymd5 = getKeyMD5();
HashMap<String, String> params = new HashMap<String, String>();
params.put("model", model);
params.put("imei", imei1);
params.put("imei2", imei2);
params.put("build", buildVersion);
if (CommonUtils.isNetworkConnected(mContext)) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST,
url,
new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(Configs.APP_NAME + " " + TAG, "Success ");
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i(Configs.APP_NAME + " " + TAG, "Error: " + error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
headers.put("Content-type", "application/json");
headers.put("Authorization", odmName + ":" + keymd5);
return headers;
}
};
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(Configs.TIME_OUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
requestQueue.add(jsonObjectRequest);
}
}
I can not find where I was wrong with the code for Volley method. Is there any problem in my Volley method?
It is difficult to say why you are facing an error .please check that url and parameters are sent correctly .once you get the error then paste error log here
Check the following link to understand it better
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

HTTP POST request in Android causing server to crash

I'm pulling my hair out trying to get this to work. I'm using OkHTTP to make a POST request to my server. However, every method I've tried of making a successful POST request with parameters, causes the server to go down, giving me a response of '503 service unavailable'. I use exterior clients to test the server, like the Advanced Rest Client extension, and it works perfectly fine.
The URL for the API is in the format of "https://mystuff-herokuapp.com/postuser" and my body parameters are "user_id", "userName", "email". I've tried adding headers to the request, changing from FormBodyEncoding() to MultiPartBuilder(), etc etc.
onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
//set toolbar as the acting action bar
Toolbar actionToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(actionToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
Intent intent = getIntent();
String photoUrl = intent.getStringExtra("photo");
String userTwitterID = intent.getStringExtra("userID");
String userName = intent.getStringExtra("name");
String userEmail = intent.getStringExtra("email");
JSONObject jObject = new JSONObject();
try {
jObject.put("user_id", userTwitterID);
jObject.put("userName", userName);
jObject.put("userEmail", userEmail);
} catch (JSONException e) {
e.printStackTrace();
}
new UserApiProcess().execute(jObject);
}
Async Task
private class UserApiProcess extends AsyncTask<Object, Void, Void>{
#Override
protected Void doInBackground(Object... strings) {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new MultipartBuilder()
.addFormDataPart("user_id", "800")
.addFormDataPart("userName", "Nick")
.addFormDataPart("email", "something#something.com")
.build();
Request request = new Request.Builder()
.url("https://mystuff.herokuapp.com/postuser")
.addHeader("Content-Type", "x-www-form-urlencoded")
.post(formBody)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
if(!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Successful Response from Advanced Rest Client
My Server Error through Android
Try this. It should work.
private class UserApiProcess extends AsyncTask<Object, Void, Void>{
#Override
protected Void doInBackground(Object... strings) {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormEncodinBuilder()
.add("user_id", "800")
.add("userName", "Nick")
.add("email", "something#something.com")
.build();
Request request = new Request.Builder()
.url("https://mystuff.herokuapp.com/postuser")
.addHeader("Content-Type", "x-www-form-urlencoded")
.post(formBody)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
if(!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

Categories

Resources