Proper Use of Keep Alive For Loop - java

I'm working to make a thread that monitors a web api to get the latest announcement via JSON. I cannot test this currently, so I'm unsure if anything needs to be changed with this. I've read through other questions but everyone else doesn't seem to be using a loop to keep getting a response.
public void run(){
try {
URL url = new URL(announcementsURL);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("GET");
http.setRequestProperty("Connection", "keep-alive");
http.setUseCaches(false);
http.setAllowUserInteraction(false);
http.setConnectTimeout(10);
http.setReadTimeout(10);
while (true){
http.connect();
int status = http.getResponseCode();
if (status == 201){
BufferedReader br = new BufferedReader(new InputStreamReader(http.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
String json = sb.toString();
JSONParser parser = new JSONParser();
JSONObject jsonResponse = (JSONObject) parser.parse(json);
if (!(lastAnnouncement == (long) jsonResponse.get("time"))){
//String announcement = (String) jsonResponse.get("message");
//TODO What to do with announcement...
}
}
http.getInputStream().close();
http.disconnect();
}
} catch (IOException | ParseException e) {
e.printStackTrace();
this.interrupt();
try {
this.join();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}

Related

In postman api works fine but in java it doesn't

I am trying to get a JSON Object from an API while using an API Url. This works perfectly when I test it in Postman, but when I try it in my Spring application, it returns 405 with message(The method is not allowed for the requested URL)
My Java Code:-
URL tokenURL = new URL("https://something.in/v1/token");
HttpURLConnection tokenConnection = (HttpURLConnection) tokenURL.openConnection();
tokenConnection.setRequestMethod("GET");
tokenConnection.setConnectTimeout(Integer.parseInt(env.getProperty
("common.webServiceCall.maxTimeOut")));
tokenConnection.setReadTimeout(Integer.parseInt(env.getProperty
("common.webServiceCall.maxTimeOut")));
tokenConnection.setRequestProperty("Content-Type", "application/json");
tokenConnection.setRequestProperty("Accept", "application/json");
tokenConnection.setRequestProperty("X-IBM-Client-Id", "45878d21-469c-b68e-34b1suds34c");
tokenConnection.setRequestProperty("X-IBM-Client-Secret", "ytGThJH4sW7hY2skhJHG65uC7xH7v645fsdfkjgFGHDFgcvhg");
tokenConnection.setDoInput(true);
tokenConnection.setDoOutput(true);
OutputStream tokenStream = null;
try {
tokenStream = tokenConnection.getOutputStream();
} catch (RemoteException e) {
e.printStackTrace();
}
try {
for(int i = 0; i < 3; i++) {
tokenConnection.connect();
if (tokenConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (tokenConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((tokenConnection.getInputStream())));
StringBuilder serviceResponse = new StringBuilder();
String serviceResponseLine;
while ((serviceResponseLine = bufferedReader.readLine()) != null) {
serviceResponse.append(serviceResponseLine);
}
tokenStream.close();
tokenConnection.disconnect();
System.out.println(serviceResponse);
} else {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader((tokenConnection.getErrorStream())));
StringBuilder serviceResponse = new StringBuilder();
String serviceResponseLine;
while ((serviceResponseLine = bufferedReader.readLine()) != null) {
serviceResponse.append(serviceResponseLine);
}
tokenStream.close();
tokenConnection.disconnect();
System.out.println(serviceResponse);
}
I have one suggestion, postman can generate source code of request for different programming languages e.g. java and JavaScript and command line tool like cURL.
I suggest use cURL gives you more verbose details that can help you in connection configuration.

Send data(Client_id=1,Staff_id=2) from android application to tomcat server

i want to send data from android application to tomcat java server.
Data is just one is client_id which is 1 and second is staff_id which is 2.
after authenticate the client id and staff id from tomcat show me a toast of success....please help...
Code is here
public class MyAsyncTasks extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// display a progress dialog for good user experiance
}
#Override
protected String doInBackground(String... params) {
// implement API in background and store the response in current variable
String current = "";
try {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://192.168.1.13:8080/digitaldisplay/s/m/data");
urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
current += (char) data;
data = isw.read();
System.out.print(current);
}
// return the data to onPostExecute method
return current;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
} catch (Exception e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
}
return current;
}
#Override
protected void onPostExecute(String s) {
Toast.makeText(Register.this, "success", Toast.LENGTH_SHORT).show();
Log.d("data", s.toString());
// dismiss the progress dialog after receiving data from API
try {
// JSON Parsing of data
JSONArray jsonArray = new JSONArray(s);
JSONObject oneObject = jsonArray.getJSONObject(0);
// Pulling items from the array
client = Integer.parseInt(oneObject.getString("client"));
staff = Integer.parseInt(oneObject.getString("staff"));
} catch (JSONException e) {
e.printStackTrace();
}
} }}
The logic in your code looks off to me. This is the pattern I usually follow when making a REST call from an activity using HttpURLConnection:
try {
String endpoint = "http://192.168.1.13:8080/digitaldisplay/s/m/data";
URL obj = new URL(endpoint);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST"); // but maybe you want GET here...
con.setConnectTimeout(10000);
con.setDoInput(true);
con.setDoOutput(true);
JSONObject inputJSON = new JSONObject();
inputJSON.put("Client_id", 1);
inputJSON.put("Staff_id", 2);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(inputJSON.toString());
writer.flush();
writer.close();
os.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response);
} catch (SocketTimeoutException se) {
// handle timeout exception
responseCode = -1;
} catch (Exception e) {
// handle general exception
responseCode = 0;
}
The only major change in adapting the above code for GET would be that you wouldn't write your input data to the connection. Instead, you would just append query parameters to the URL. I am possibly guessing that you need POST here, since your URL doesn't have any query parameters in it.

how to return a json string in php for using it in java

I want wrote an API in php for using it in my android app. In the php side I do this for return info in an array
echo json_encode($array)
result of this code is like this, see online result in this link:
{"value":[{"id":"1","name":"kufta","meal":"1","photo_id":"","explanation":"xoshmazas","foodtime":"0000-00-0000:00:00"},{"id":"2","name":"\r\nAsh","meal":"2","photo_id":"","explanation":"sdfdsfsdfdsfdsfsdf","foodtime":"2017-06-26 14:00:00"},{"id":"3","name":"kabab","meal":"3","photo_id":"","explanation":"kabab kheili khoshmaze ast","foodtime":"2017-06-29 00:00:00"}]}
but in java side when I load this, app crash but when I use this json string in this site. Android app works fine
my java code for reading the url content
public class WebService {
private String connectToServer(String address, String requestMethod) {
try {
URL url = new URL(address);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod(requestMethod);
return inputStreamToString(httpURLConnection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private String inputStreamToString(InputStream inputStream) {
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String nextLine;
while ((nextLine = reader.readLine()) != null) {
stringBuilder.append(nextLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
line 23 : public List<FoodModel> getFoods(){ <-----------Error is here
String response = connectToServer("http://mtg1376.gigfa.com/api/food?day=All","GET");
if(response != null){
List<FoodModel> foodList = new ArrayList<😠);
try{
JSONObject mainObject = new JSONObject(response);
JSONArray foodArray = mainObject.getJSONArray("value");
for(int i = 0 ; i< foodArray.length();i++){
JSONObject foodObject = foodArray.getJSONObject(i);
FoodModel foodModel = new FoodModel();
foodModel.id = foodObject.getString("id");
foodModel.name = foodObject.getString("name");
foodModel.meal = foodObject.getString("meal");
foodModel.photo_id = foodObject.getString("photo_id");
foodModel.explanation = foodObject.getString("explanation");
foodModel.foodtime=foodObject.getString("foodtime");
foodList.add(foodModel);
}
return foodList;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null; }
}
java error log : https://ibb.co/hQneXk
whats the problem?

AsyncTask LIFX Bulb response

I have got problem with read output form request.
public JSONArray listLights()
{
try
{
URL adres = new URL("https://api.lifx.com/v1/lights/all");
HttpURLConnection polaczenie = (HttpURLConnection) adres.openConnection();
polaczenie.setRequestProperty("Authorization", "Bearer " + apiKey);
polaczenie.setRequestMethod("GET");
BufferedReader wejscie = new BufferedReader(new InputStreamReader((polaczenie.getInputStream())));
StringBuilder odpowiedz = new StringBuilder();
String json;
while ((json = wejscie.readLine()) != null)
odpowiedz.append(json);
wejscie.close();
return new JSONArray(odpowiedz.toString());
}
catch (Exception wyjatek)
{
wyjatek.printStackTrace();
}
return new JSONArray();
}
StackTrace
I added to AndroidManifest Internet access too.
Welcome to leave any comments. :P
EDIT:
I google internet and found partial solution. Added AsyncTask, but now I'm receiving '429' response code.
public class JSONTask extends AsyncTask<String, String, String>
{
String apiKey = "blah_blah_blah";
String txtresult;
#Override
protected String doInBackground(String... params) {
HttpsURLConnection connection = null;
BufferedReader reader = null;
try
{
URL adres = new URL(params[0]);
HttpsURLConnection polaczenie = (HttpsURLConnection) adres.openConnection();
polaczenie.setRequestProperty("Authorization", "Bearer " + apiKey);
polaczenie.setRequestMethod("GET");
System.out.println(polaczenie.getResponseCode());
InputStream stream = polaczenie.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null)
{
buffer.append(line);
}
return buffer.toString();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally {
if (connection != null)
connection.disconnect();
try
{
if (reader != null)
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s)
{
super.onPostExecute(s);
widok.setText(s);
}
}
My current StackTrace
EDIT2:
New day, new surprise. I figure out that I'm making connection with Bulb once/twice on every 10 attempts. Any ideas?
HTTP Status code 429 means too many requests in a given an amount of time. So how many requests exactly are you doing?
android.os.NetworkOnMainThreadException it means, that You have to make a htttp request from another threat than UIthread. Why are you using async task ?
Edit: You can also try make a call from postman and maybe You will see the problem.
In the end, everything is working. Problem was on the side of bulb or Lifx Cloud.

How to pass and read string from android to sql using JSON

Previously, i can access the string from php remotely. I find it difficult at first but AsyncTask did the work for me. Now, i can access the result of the query from php to sql server. But I would like to pass a string from my java class to php and as I googled some information, i saw some JSON post and get codes but i can't clearly understand them. Here's my code:
protected String doInBackground(Void... params) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
HttpURLConnection urlConnection = null;
String line;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
InputStream in = urlConnection.getInputStream();
br = new BufferedReader(new InputStreamReader(in));
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return sb.toString();
The string is contained in "sb.toString()". Now how would I add a JSON something in my code to send string from java to php, and also get the result string from php to java as well. Thanks in advance for any help.
If you receive response as JSON format from server, make the json string to JSONObject first. And then read the json data for your use.
try {
JSONObject obj = new JSONObject(sb.toString()); // make string to json obj
Iterator iter = obj.keys(); // get all keys from json obj and iterating
while(iter.hasNext()){
String key = (String)iter.next();
String str = obj.get(key).toString();
// write your code
}
} catch(Exception e) {
e.printStackTrace();
}
Your code already contains the answer of your question. After make url connection, just add parameter for sending your data to server with OutputStreamWriter as like you did for receive the response with InpustStreamReader.
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
HttpURLConnection urlConnection = null;
String line;
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
// wrtie params
OutputStreamWriter we = new OutputStreamWriter(urlConnection.getOutPutStream());
wr.write(data); // data (make json obj to 'key=value' string)
wr.flush();
wr.close();
// read response
InputStream in = urlConnection.getInputStream();
br = new BufferedReader(new InputStreamReader(in));
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}enter code here

Categories