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.
Related
I'm following an example of using the Reddit API in an Android app. I'm using Android Studio and Java. I have a link which returns a JSON object on a GET request (let's say http://www.reddit.com/r/dragonforce/.json), and the tutorial has this piece of code:
public static HttpURLConnection getConnection(String url){
System.out.println("URL: "+url);
HttpURLConnection hcon = null;
try {
hcon=(HttpURLConnection) new URL(url).openConnection();
hcon.setReadTimeout(30000); // Timeout at 30 seconds
hcon.setRequestProperty("User-Agent", "Alien V1.0");
} catch (MalformedURLException e) {
Log.e("getConnection()",
"Invalid URL: "+e.toString());
} catch (IOException e) {
Log.e("getConnection()",
"Could not connect: "+e.toString());
}
return hcon;
}
and
public static String readContents(String url){
HttpURLConnection hcon=getConnection(url);
if(hcon==null) return null;
try{
StringBuffer sb=new StringBuffer(8192);
String tmp="";
BufferedReader br=new BufferedReader(
new InputStreamReader(
hcon.getInputStream()
)
);
tmp = br.readLine();
while(tmp !=null) {
sb.append(tmp).append("\n");
tmp = br.readLine();
}
br.close();
return sb.toString();
}catch(IOException e){
Log.d("READ FAILED", e.toString());
return null;
}
}
I separated the tmp assignment for debug purposes. The problem is that nothing is read from the inputStream, and it returns an empty buffer to the JSONObject parser, resulting in JSONException end of input at character 0 of. I have user-permission in the Manifest for INTERNET, and the syntax for reading from the URL seems to be backed up by other sources on the internet, but it still seems something is amiss. Any help would be appreciated.
For anyone who is reading this down the line, the problem was that the URL in the tutorial was using HTTP instead of HTTPS, leading to a redirect response code and wasn't returning anything.
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
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 !
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/
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