Created
October 30, 2018 22:15
-
-
Save arianimartins/b8377a90aa633c4338e2914e8de07c5c to your computer and use it in GitHub Desktop.
Android Alura iChat - Examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//De envio | |
new Thread(new Runnable() { | |
@Override | |
public void run() { | |
String texto = mensagem.getTexto(); | |
try { | |
URL url = new URL("http://address/polling"); | |
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); | |
httpConnection.setRequestMethod("POST"); | |
httpConnection.setRequestProperty("Content-type", "application/json"); | |
JSONStringer json = new JSONStringer() | |
.object() | |
.key("text") | |
.value(texto) | |
.key("id") | |
.value(mensagem.getId()) | |
.endObject(); | |
OutputStream saida = httpConnection.getOutputStream(); | |
PrintStream ps = new PrintStream(saida); | |
ps.println(json.toString()); | |
httpConnection.connect(); | |
httpConnection.getInputStream(); | |
} catch (Exception e) { | |
throw new RuntimeException(e); | |
} | |
} | |
}).start(); | |
//De recebimento | |
new Thread(new Runnable() { | |
@Override | |
public void run() { | |
try { | |
URL url = new URL("http://172.21.180.209:8080/polling"); | |
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(); | |
httpConnection.setRequestMethod("GET"); | |
httpConnection.setRequestProperty("Accept", "application/json"); | |
httpConnection.connect(); | |
Scanner scanner = new Scanner(httpConnection.getInputStream()); | |
StringBuilder builder = new StringBuilder(); | |
while (scanner.hasNextLine()){ | |
builder.append(scanner.nextLine()); | |
} | |
String json = builder.toString(); | |
JSONObject jsonObject = new JSONObject(json); | |
final Mensagem mensagem = new Mensagem(jsonObject.getInt("id"),jsonObject.getString("text")); | |
activity.runOnUiThread(new Runnable() { | |
@Override | |
public void run() { | |
activity.colocaNaList(mensagem); | |
} | |
}); | |
} catch (Exception e) { | |
throw new RuntimeException(e); | |
} | |
} | |
}).start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment