2016-01-09 51 views
0

我正在製作一個android應用程序,可以將信息從客戶端發送到服務器。我試圖從客戶端發送JSON對象到服務器端,但我不知道如何將它保存在服務器端,然後再次將其發送回客戶端。如何保存我從客戶端發送到服務器的字符串值?

我是新來的Heroku服務器和Java EE,所以我不知道如何在服務器端代碼。

下面是客戶端代碼:

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); 
    } 
} 

}

現在我必須將其保存在Heroku的服務器:

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()); 
    } 

} 

如果你能告訴我該如何應對它回到客戶端會很好。

謝謝。

回答

2

如果您需要保存在服務器上的東西,你會希望把它放在一個數據庫中。這裏是關於Connecting to Relational Databases on Heroku with Java的文章。

+0

謝謝,我閱讀文檔,它是有用的,但我想我會遷移我的代碼來解析數據庫,因爲他們接受JSON作爲參數,這將節省我的一些工作。 – MuhammadNe

相關問題