Segue abaixo os códigos:
package com.example.teammobile.exercicioagenda.web;
import android.support.annotation.Nullable;
import java.io.IOException;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
/**
* Created by Felippe Neves on 28/08/2017.
*/
public class WebClient {
public String post(String json){
String endereco = "https://www.caelum.com.br/mobile";
return realizaConexao(json, endereco);
}
public void insere(String js) {
String endereco ="http://meuip:8080/aluno";
realizaConexao(js, endereco);
}
@Nullable
private String realizaConexao(String json, String endereco) {
try {
URL url = new URL(endereco);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-type", "aplication/json");
connection.setRequestProperty("Accept", "aplication/json");
connection.setDoOutput(true);
connection.setDoInput(true);
PrintStream output = new PrintStream(connection.getOutputStream());
output.println(json);
connection.connect();
Scanner scanner = new Scanner(connection.getInputStream());
String resposta = scanner.next();
return resposta;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
package com.example.teammobile.exercicioagenda.tasks;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import com.example.teammobile.exercicioagenda.Modelo.Aluno;
import com.example.teammobile.exercicioagenda.web.WebClient;
import com.example.teammobile.exercicioagenda.converter.AlunoConverter;
import com.example.teammobile.exercicioagenda.dao.AlunoDAO;
import java.util.List;
/**
* Created by Felippe Neves on 28/08/2017.
*/
public class EnviarAlunosTask extends AsyncTask<Void, Void, String> {
private Context context;
private ProgressDialog dialog;
public EnviarAlunosTask(Context context) {
this.context = context;
}
@Override
protected void onPreExecute() {
dialog = ProgressDialog.show(context, "Aguarde", "Enviando alunos...", true, true);
}
@Override
protected String doInBackground(Void... objects) {
WebClient client = new WebClient();
AlunoDAO dao = new AlunoDAO(context);
List<Aluno> alunos = dao.buscaAlunos();
dao.close();
AlunoConverter converter = new AlunoConverter();
String json = converter.converteParaJSON(alunos);
String resposta = client.post(json);
//Toast.makeText(context, resposta, Toast.LENGTH_SHORT).show();
return resposta;
}
@Override
protected void onPostExecute(String resposta) {
dialog.dismiss();
Toast.makeText(context, resposta, Toast.LENGTH_LONG).show();
}
}
new InsereAlunoTask(aluno).execute();