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.
Related
I am currently creating my first Android app with Java. I make two API calls to a Loxone Music Server (based on "/audio/X/volume/-Y" -> https://www.loxone.com/dede/kb/loxone-music-server/) to change the volume of the room. The calls are simple GET requests to different URLs. The call is made using two different buttons. Once on the URL "http://xx.xx.xx.xx:7091/audio/9/volume/+5" to increase the volume by 5% and with the URL "http://xx.xx.xx.xx:7091/audio/9/volume/-5" to decrease the volume by 5%. Both calls are executed cleanly. My problem is, depending on which button I click first, that executes the request. When I click the other button, the same request is received on the music server. That is, if I increase the volume first, when I click on the decrease volume button, the request is sent from the increase to the music server, even though the log output shows the correct URL.
Currently, I am stuck because I don't know what I am doing wrong. In the log, I see that different request URL are called. However, somehow via a cache mechanism or proxy, always the same request arrive at the music server. If I execute the two calls in the Postman, they work fine.
For the implementation, I have already tried different variants. However, with the same result. I have the same behavior with StringRequest in combination with and without queue (volley), or also with a simple variant with HttpURLConnection.
StringRequest
public void get(String url, String username, String pwd) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (null != response) {
Log.d(TAG, "GET");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "ERROR");
}
}){
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put(
"Authorization",
String.format("Basic %s", Base64.encodeToString(
String.format("%s:%s", username, pwd).getBytes(), Base64.DEFAULT)));
return params;
}
};
queue.add( request );
}
Simple Variant
public void sendSimpleGET( String uri) {
try{
URL obj = new URL(uri);
HttpURLConnection con = (HttpURLConnection) obj.openConnection(Proxy.NO_PROXY);
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "LoxoneSuiteApp");
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
// success
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("GET request not worked");
}
} catch (IOException e) {
e.printStackTrace();
toastMessage("Error: " + e.getMessage());
}
}
I had 2 pages: first one is login page and second is category page. In login API after entering the credentials, I am getting the response as sesssion id from response header.
The sesssion id will be saved and it will use for further API calls. I am trying to call second API (category page). In this page, as an input am passing the saved session id in the request header. Getting response as "session expired". Also tried to pass Set-Cookie: PHPSESSID=d9f9sdkfjs9 in the request header. but it didn't work.
Note :
I am experiencing this issue in production environment only (SSL included)
I am using volley library for handling APIs.
public void fnCallLoginAPI() {
try {
//DEMO URL
//final String URL="http://demo.io/api/api.php?m=login";
//LIVE URL
final String URL = "https://www.live.com/shop/api/api.php?m=login";
final String requestBody = "email=abc.b#xyz.com" + "&password=43443==" + "&strPlatform=i" + "&strDeviceToken=null";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String strResponse = response;
System.out.println("THE RESPONSE IS in PROFILE IS" + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Cookie", "PHPSESSID=" + sessionID);
return headers;
}
#Override
public byte[] getBody() throws AuthFailureError {
byte[] body = new byte[0];
try {
System.out.println("THE REQIEST BODY IS" + requestBody);
body = requestBody.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e("TAG", "Unable to gets bytes from JSON", e.fillInStackTrace());
}
return body;
}
};
AppApplication.getInstance().addToRequestQueue(stringRequest, "assignment");
} catch (Exception e) {
}
}
public void fnCallCateGoryAPI(){
try { final String URL ="https://www.live.com/shop/api/api.php?m=getcategories";
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String strResponse = response;
System.out.println("THE RESPONSE IS in PROFILE IS" + response);
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(strResponse);
sessionID = jsonObj.optString("session_id");
System.out.print("sessionID" + sessionID);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
};
AppApplication.getInstance().addToRequestQueue(stringRequest, "assignment");
} catch (Exception e) {}
}}
#fazil try after increasing the token expiration time from the backend
#fazil : I was facing something similar in my projects too and the reason i understood was actually due to multiple header values set under same key "Set-Cookie".
Please do check this in your logs.
Also, make sure that you have set the headers properly in your request(check the logs of request and response from your Server).
If everything implemented is correct and the issue is due to multiple values in the same header you need to check this implementation of volley : https://github.com/georgiecasey/android-volley-duplicateheadersfix
i am making FriendManagementApp. I want to fetch response from the local host.I am using gson,volley,recyclerview but I am not getting response.
private void requestJsonObject() throws AuthFailureError
{
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://192.168.1.50:8080/*************/";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
// Log.d(TAG, "Response " + response);
GsonBuilder builder = new GsonBuilder();
Gson mGson = builder.create();
List<FriendsData> posts = new ArrayList<FriendsData>();
posts = Arrays.asList(mGson.fromJson(response, FriendsData[].class));
Log.i("MainActivity", posts.size() + " posts loaded.");
for (FriendsData data : posts) {
Log.i("MainActivity", data.getId() + ": " + data.getFirstname() + ": " + data.getLastname() + ":" + data.getContact());
adapter = new RecyclerViewAdapter(MainActivity.this, posts);
//recyclerView.setAdapter(adapter);
// recyclerView.getAdapter().addAll(posts);
// recyclerView.getAdapter().notifyDataSetChaged();
System.out.println(data.getId());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error " + error.getMessage());
System.out.print(error.getMessage());
}
});
queue.add(stringRequest);
}
If you are using emulator to connect to local machine use 10.0.2.2 IP address instead of 192.168.1.50. Check this link
I am assume that you installed LAMP server on your local machine.
You should open your local host's 8080 port for inbound rules.
Try to connect that url with your local browser.
If it is ok, put your LAMP server online. See Detail
Am getting 400 server error for volley get request for below url
http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ('AEDALL')&format=json&env=store://datatables.org/alltableswithkeys&callback=
when i hit the same url from rest client its giving json response
Here is my code for volley request
private void convertCurrenctVolleyTask(String from, final String to, final String amount) {
String url_yahoo = "http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ('"+from+to+"')&format=json&env=store://datatables.org/alltableswithkeys&callback=";
final ProgressDialog progressDialog;
progressDialog = new ProgressDialog(CurrencyConverter.this);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(true);
progressDialog.show();
JsonObjectRequest GetCurrenciesjsObjRequest = new JsonObjectRequest(
Request.Method.GET, url_yahoo, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressDialog.cancel();
if (response != null) {
parseGetCurrencyResp(response,to,amount);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.cancel();
Toast.makeText(CurrencyConverter.this,
"Server error..", Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
ConfigVolley.getInstance().addToRequestQueue(GetCurrenciesjsObjRequest);
}
Any help appreciated
You will need to replace all occurences of a space(" ") with the %20 url_yahoo = url_yahoo.replace(" ", "%20");
That is not a properly formatted URL. You need to encode your URL parameters so that they do not contain invalid characters.
Try using URLEncoder before using your url_yahoo like so:
String query = "select * from yahoo.finance.xchange where pair in ('"+from+to+"')";
query = URLEncoder.encode(query, "utf-8");
String env = "store://datatables.org/alltableswithkeys&callback=";
env = URLEncoder.encode(query, "utf-8");
url_yahoo = "http://query.yahooapis.com/v1/public/yql?q=" + query + "&format=json&env=" + env;
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();