Asterisk Manager Interface from Android Device - android

I have set up the Asterisk Server properly for allowing GUI interface, to check this I have tried & tested an already available Application for Android & tested the same with my browser.
I am able to login & view the files.
eg.
http://192.168.8.x:8088/asterisk/rawman?action=getconfig&filename=users.conf
this commands shows me the user.conf file.
However the same commands does not works from my Android Application. It results in
Response: Error
Message: Permission denied
my code:
1st button click:
try{
new mygoogleSearch().execute(http://192.168.8.x:8088/asterisk/rawman?action=login&username=tismo&secret=tismo123);
}
catch(Exception e) {
Log.v("Exception google search","Exception:"+e.getMessage());
}
this returns:
03-27 17:27:09.468: E/GoogleSearch(21686): Response: SuccessMessage: Authentication accepted
On 2nd Button click:
try{
new Execute().execute("http://192.168.8.4:8088/asterisk/rawman?action=getconfig&filename=test.conf");
} catch(Exception e) {
Log.v("Exception google search","Exception:"+e.getMessage());
}
class mygoogleSearch extends AsyncTask {
protected String doInBackground(String... searchKey) {
;
String cmd = searchKey[0];
try {
return action(cmd);
} catch(Exception e) {
Log.v("Exception ",
"Exception:"+e.getMessage());
return "";
}
}
private String action(String uRL)
throws MalformedURLException, IOException {
String newFeed= uRL;
StringBuilder response = new StringBuilder();
URL url = new URL(newFeed);
HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
httpconn.setUseCaches(false);
//httpconn.setRequestProperty("Cache", "false");
if(httpconn.getResponseCode()==HttpURLConnection.HTTP_OK) {
BufferedReader input = new BufferedReader(
new InputStreamReader(httpconn.getInputStream()),
8192);
String strLine = null;
while ((strLine = input.readLine()) != null) {
response.append(strLine);
}
input.close();
}
return response.toString();
}
this returns:
03-27 17:28:31.808: E/GoogleSearch(21800): Response: ErrorMessage: Permission denied

You need a CookieManager to connect to the same session.
Quote from the asteriskbook "the definitive Guide"
"The LOGIN command authenticates credentials for the Manager interface’s HTML view.
Once you are logged in, Asterisk stores a cookie on your browser (valid for the length of the httptimeout setting). This cookie is used to connect to the same session."
Update: Examples of a CookieManager Storage to mimic the Browser:
How to use Cookies with HttpUrlConnection, persist Cookies using HttpUrlConnection

Related

Log message to sumo logic from Android client

I've got a requirement to log message from the Android client. Is there any sumo logic API to log message from the Android application?
You can post your log message/ any message from your Android application to Summo Logic cloud-based log management.
Summo Logic provides Web Services/ REST to perform POST, GET Request.
You just need to post your data on the request body and mention your
Sumo collection endpoint as well as UniqueHTTPCollectorCode.
REST Service/ Web Service : https://[SumoEndpoint]/receiver/v1/http/[UniqueHTTPCollectorCode]
For Instance:
"https://endpoint1.collection.us2.sumologic.com/receiver/v1/http/SanTC12dhaV1oma90Vvb..."
You can use Retorfit / Volley library for REST Communication .
I have given a below pseudo code which conveys the basic REST Communication in background through Android Async Task.
I strictly recommend to use the above mentioned libraries.
public static String performPostRequest(String summoUrl, String payload,
Context context) throws IOException {
URL url = new URL(summoUrl);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
String line;
StringBuffer jsonString = new StringBuffer();
uc.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
uc.setRequestMethod("POST");
uc.setDoInput(true);
uc.setInstanceFollowRedirects(false);
uc.connect();
OutputStreamWriter writer = new OutputStreamWriter(uc.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));
while((line = br.readLine()) != null){
jsonString.append(line);
}
br.close();
} catch (Exception ex) {
ex.printStackTrace();
}
uc.disconnect();
return jsonString.toString();
}
Async task
new AsyncTask<String, String, String>() {
#Override
protected String doInBackground(String... params) {
try {
String response = makePostRequest(""https://endpoint1.collection.us2.sumologic.com/receiver/v1/http/ZaVnC4dhaV1oma90Vvb..."",
// Sample JSON Data "
{ \"organization": \"organization.name\",
\"environment": \"environment.name\",
\"apiProduct": \("apiproduct.name"),
\"proxyName": \("apiproxy.name"),
\"appName": \("developer.app.name"),
\"verb": \("request.verb"),
\"url": '' + \("client.scheme") + '://' + \("request.header.host") + \("request.uri"),
\"responseCode": \("message.status.code"),
\"responseReason": \("message.reason.phrase"),
\"clientLatency": total_client_time,
\"targetLatency": total_target_time,
\"totalLatency": total_request_time
}", getApplicationContext());
// Hard coded Success as response from Server, replace with this as per your need
return "Success";
} catch (IOException exception) {
exception.printStackTrace();
return exception.getMessage();
}
}
}.execute("");
For more information, Please refer the documentation from Official Sumo Webpage
https://help.sumologic.com/Send-Data/Sources/02Sources-for-Hosted-Collectors/HTTP-Source/Upload-Data-to-an-HTTP-Source

HttpURLConnection where do I put the API key?

I'm working on an android application and I am trying to retrieve JSON objects from a web API. I am able to read public endpoints and display the results. However, when I try to read private endpoints, I get an error "Permission Denied" in the console. I have read the API document and it states to put the api key in the header. It gives an example:
# Example with curl
curl -X GET https://wger.de/api/v2/workout/ \
-H 'Authorization: Token ae45ad5c68667c4f3a5bfcd983b629875732ecbb'
This is my post request class:
public void sendPostRequest (String where) {
URL loc = null;
HttpURLConnection conn = null;
InputStreamReader is;
BufferedReader in;
try {
loc = new URL(where);
}
catch (MalformedURLException ex) {
return;
}
try {
conn = (HttpURLConnection)loc.openConnection();
conn.addRequestProperty("Authorization","my-api-key");
is = new InputStreamReader (conn.getInputStream(), "UTF-8");
in = new BufferedReader (is);
readResponse (in);
}
catch (IOException ex) {
}
finally {
conn.disconnect();
}
}
I tried to add conn.addRequestProperty("Authorization","my-api-key"); but my application fails when trying to recive the JSON object.

Android: HttpUrlConnection object returns error 301 after connection

I'm trying to connect to a web API using a URL. However, I get a 301 error from the server (Moved Permanently), although the provided URL works very well with no errors when I try it in my browser.
Here is the code that builds the URL:
public Loader<List<Earthquake>> onCreateLoader(int i, Bundle bundle) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String minMagnitude = sharedPrefs.getString(
getString(R.string.settings_min_magnitude_key),
getString(R.string.settings_min_magnitude_default));
String orderBy = sharedPrefs.getString(
getString(R.string.settings_order_by_key),
getString(R.string.settings_order_by_default)
);
Uri baseUri = Uri.parse(USGS_REQUEST_URL);
Uri.Builder uriBuilder = baseUri.buildUpon();
uriBuilder.appendQueryParameter("format", "geojson");
uriBuilder.appendQueryParameter("limit", "10");
uriBuilder.appendQueryParameter("minmag", minMagnitude);
uriBuilder.appendQueryParameter("orderby", orderBy);
Log.i ("the uri is ", uriBuilder.toString());
return new EarthquakeLoader(this, uriBuilder.toString());
}
Here is the code that tries to connect to the resource represented by the URL:
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
Log.i("The received url is " , url +"");
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode()); //this log returns 301
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// Closing the input stream could throw an IOException, which is why
// the makeHttpRequest(URL url) method signature specifies than an IOException
// could be thrown.
inputStream.close();
}
}
return jsonResponse;
}
I could know that the connection returns status code of 301 from the log provided in the case when the status code is not 200. I have also logged the generated URL, I copied it from the logcat and tried it in my browser and it worked well. Here is the built URL: http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&limit=10&minmag=6&orderby=magnitude
I checked this question: Android HttpURLConnection receives HTTP 301 response code but it wasn't clear to me what is the solution for the problem.
Can you please help me identify and solve the problem?
UPDATE: As greenapps indicated in his comment, the connection is done through https. That comment identified the problem and helped me fix the code.
In my code, the string I used to build the basic URL, had the protocol value as http not https, it was:
private static final String USGS_REQUEST_URL =
"http://earthquake.usgs.gov/fdsnws/event/1/query";
After reading greenapps comment, I just changed the protocol part in the string to https, so it became:
private static final String USGS_REQUEST_URL =
"https://earthquake.usgs.gov/fdsnws/event/1/query";
That solved the problem.
Thanks.
If you click your http link here you will see that the browser shows a https page. You better use that url directly as there is redirection now.
This is because the address http to https transferred.
To avoid this, you need to convert the request address to https.

java.io.EOFException on Android Client (API 23) when POSTing Object to Jersey

I want to implement a basic authentication using an Android Client and a Glassfish 4.1.1 Server (communicating through REST-Service).
The Service is working quite well (proven by POSTMAN and another C#-Client) but on Android, it's driven me crazy by now.
It also appears that the object-to-send is received as 'null' on the server side, also an annoying "EOFException" is thrown on the Android Side.
Server side (works fine)
#POST
#Consumes({MediaType.APPLICATION_JSON})
#Produces({MediaType.APPLICATION_JSON})
public Account validate(Account acc)
{
Account a = null;
a = Database.getInstance().getAccountByUserPw(acc);
return a;
}
Android Client:
public Account postData(String JSONtoSend)
{
URL url;
Account get = new Account();
try {
url = new URL("http://192.xxx.xxx.x:18080/HolidayOutServer/webresources/validateacc");
HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
urlCon.setRequestMethod("POST");
urlCon.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlCon.setRequestProperty("Accept", "application/json; charset=UTF-8");
urlCon.setDoOutput(true); // to be able to write.
urlCon.setDoInput(true); // to be able to read.
OutputStreamWriter out = new OutputStreamWriter(urlCon.getOutputStream());
out.write(JSONtoSend);
ObjectInputStream ois = new ObjectInputStream(urlCon.getInputStream());
get = (Account) ois.readObject();
return get;
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return get;
}
which is called within this:
class help extends AsyncTask<String, Void, Account>
{
#Override
protected Account doInBackground(String... params) {
return postData(new Gson().toJson(new Account("aleqs", "lexx", -2)));
}
}
Problems in a nutshell:
Jersey Server receives null
Android throws this ridiculous EOFException.
Can somebody help ?
Thanks in advance,
John.
Ok, I managed to find a solution here after hours.
This code works for me:
try( DataOutputStream wr = new DataOutputStream( urlCon.getOutputStream())) {
wr.write(new Gson().toJson(new Account("aleqs", "lexx", -2)).getBytes());
}
Reader in = new BufferedReader(new InputStreamReader(urlCon.getInputStream(), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (int c; (c = in.read()) >= 0;)
sb.append((char)c);
response = sb.toString();
return response;
} catch (IOException e) {
e.printStackTrace();
}
return response;
Change the return type of "donInBackGround" to String and let the helper class extend -String, Void, String-.
MOST IMPORTANT: CHECK IF YOUR ATTRIBUTES ON CLIENT SIDE (eg. id, name, ..) match with those from SERVER SIDE.
Consider cap locks and so on..
Cheers !

Connect Android App to Github API

I've been checking around for some time, but still can't find information on this how exactly to connect my android app to the Github API. I had it registered, had a token as well, read about the endpoints and everything, but cannot understand where the token to be used. May somebody give me a hint?
I've used below code to connect to GitHub Search Repo API in my android app.
//Method 1: To Authorize API access for all HTTP call
//Uncomment this part of code and input your username and password
// Authenticator.setDefault(new Authenticator() {
// #Override
// protected PasswordAuthentication getPasswordAuthentication() {
// return new PasswordAuthentication("username", "password".toCharArray());
// }
// });
HttpURLConnection urlConnection;
URL url;
InputStream inputStream;
try{
url = new URL("https://api.github.com/search/repositories?q="+"searchText");
urlConnection = (HttpURLConnection) url.openConnection();
//Method 2: To Authorize API access while making HTTP request
//Uncomment this part of code and input your username and password
// String basicAuth = "Basic "+Base64.encodeToString("username:password".getBytes(), Base64.NO_WRAP);
// urlConnection.setRequestProperty ("Authorization", basicAuth);
//set request type
urlConnection.setRequestMethod("GET");
//if you uncomment the following line GitHub API will not respond
// urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
//check for HTTP response
int httpStatus = urlConnection.getResponseCode();
//if HTTP response is 200 i.e. HTTP_OK read inputstream else read errorstream
if (httpStatus != HttpURLConnection.HTTP_OK) {
inputStream = urlConnection.getErrorStream();
//print GitHub api hearder data
Map<String, List<String>> map = urlConnection.getHeaderFields();
System.out.println("Printing Response Header...\n");
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
System.out.println(entry.getKey()
+ " : " + entry.getValue());
}
}
else {
inputStream = urlConnection.getInputStream();
}
//read inputstream
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String temp,response="";
while((temp = bufferedReader.readLine())!=null){
response+=temp;
}
//GitHub api has limit to access over http.
//Api rate limit is 10req/min for unauthenticated user and 30req/min is for authenticated user
boolean apiLimitExceeded = "false";
if(response.contains("API rate limit exceeded")){
apiLimitExceeded =true;
}else {
//convert data string into JSONObject
JSONObject obj = (JSONObject) new JSONTokener(response).nextValue();
JSONArray items = obj.getJSONArray("items");
//total result count and result status
total_count = obj.getString("total_count");
incomplete_results = obj.getString("incomplete_results");
}
urlConnection.disconnect();
} catch (MalformedURLException | ProtocolException | JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Check out my GitHub project to get a complete idea on how to use GitHub search repo API in Android App.
Link: https://github.com/kvipul/Search-GitHub-Repo
There are many filters that GitHub API provides. Check out the Documentation of GitHub search API for more details -https://developer.github.com/v3/search/

Categories

Resources