问题描述:

I am making an android application that sends information from client to server. I am trying to send JSON object from client side to server side, but I don't know how to save it in the server side and then send it back again to the client side.

I am new to Heroku server and java ee, so I don't know how to code the server side.

Here is the client side code :

public class JsonHeroku {

public void executeGet()

{

new JsonAsyncTask().execute();

}

class JsonAsyncTask extends AsyncTask<Void, Void, String> {

protected void onPreExecute() {

}

@Override

protected String doInBackground(Void... params) {

try {

URL url;

URLConnection urlConn;

DataOutputStream printout;

DataInputStream input;

url = new URL ("https://shrouded-lake-7996.herokuapp.com/json");

urlConn = url.openConnection();

urlConn.setDoInput (true);

urlConn.setDoOutput (true);

urlConn.setUseCaches (false);

urlConn.setRequestProperty("Content-Type","application/json");

urlConn.setRequestProperty("Host", "android.schoolportal.gr");

urlConn.connect();

//Create JSONObject here

JSONObject jsonParam = new JSONObject();

jsonParam.put("ID", "25");

jsonParam.put("description", "Real");

jsonParam.put("enable", "true");

String str = jsonParam.toString();

byte[] data=str.getBytes("UTF-8");

// Send POST output.

printout = new DataOutputStream(urlConn.getOutputStream ());

printout.write(data);

printout.flush ();

printout.close ();

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

} catch (JSONException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

protected void onPostExecute(String content) {

System.out.println("DONE ----------------------------");

System.out.println(content);

}

}

}

Now I must save it in the Heroku server :

public class Main {

public static void main(String[] args) {

port(Integer.valueOf(System.getenv("PORT")));

staticFileLocation("/public");

get("/parse", (req, res) -> {

// What do i write here?

return "Hey baby";

});

get("/", (request, response) -> {

Map<String, Object> attributes = new HashMap<>();

attributes.put("message", "Hello World!");

return new ModelAndView(attributes, "index.ftl");

}, new FreeMarkerEngine());

}

}

And if you can tell me how to respond it back to the client side would be great.

Thank you.

网友答案:

If you need to save something on the server, you'll want to put it in a database. Here is an article on Connecting to Relational Databases on Heroku with Java.

相关阅读:
Top