Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Passings the arguments, the functions will, assyncronously create a comment in database
- * @param author id of author
- * @param text text of comment
- * @param date_hour date of cooment
- * @param post id of post where the comment will be made
- * @return return the comment created ou null if any error
- * @throws IOException
- * @throws ExecutionException
- * @throws InterruptedException
- */
- public static Comment addComment(final long author, final String text, final String date_hour, final long post) throws IOException, ExecutionException, InterruptedException {
- AsyncTask<Void, Void, Comment> task = new AsyncTask<Void, Void, Comment>() {
- protected Comment doInBackground(Void... params) {
- URL url;
- Comment ret = null;
- try {
- url = new URL(RequestUtils.SERVERURL+ "/comment/add");
- HttpURLConnection con = (HttpURLConnection) url.openConnection();
- con.setDoOutput(true);
- con.setDoInput(true);
- con.setRequestMethod("POST");
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- //MUST INCLUDE HEADER
- baos.write(RequestUtils.header());
- baos.write(RequestUtils.data(TEXT_COL_DB, text));
- baos.write(RequestUtils.data(DATE_HOUR_COL_DB, date_hour));
- baos.write(RequestUtils.data(AUTHOR_COL_DB, String.valueOf(author)));
- baos.write(RequestUtils.data(POST_COL_DB, String.valueOf(post)));
- //MUST INCLUDE endRequest
- baos.write(RequestUtils.endRequest());
- byte[] to_stream = baos.toByteArray();
- baos.close();
- con.setFixedLengthStreamingMode(to_stream.length);
- con.setRequestProperty("Connection", "Keep-Alive");
- con.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
- con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + RequestUtils.BOUNDARY);
- con.getOutputStream().write(to_stream);
- int code = con.getResponseCode();
- if(code == HttpURLConnection.HTTP_OK){
- String jsonString = RequestUtils.readStream(con.getInputStream());
- ret = Comment.getFromJson(jsonString);
- }else if(code == HttpURLConnection.HTTP_INTERNAL_ERROR){
- String out = RequestUtils.readStream(con.getErrorStream());
- Log.e("myDebug", out);
- }
- con.disconnect();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (ParseException e) {
- e.printStackTrace();
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return ret;
- }
- };
- task.execute();
- return task.get();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement