Skip to content

Instantly share code, notes, and snippets.

@nenodias
Last active October 7, 2016 18:12
Show Gist options
  • Save nenodias/5d80faf58e03fcdabad4ef0cdae57d60 to your computer and use it in GitHub Desktop.
Save nenodias/5d80faf58e03fcdabad4ef0cdae57d60 to your computer and use it in GitHub Desktop.
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by hdias on 07/10/16.
*
*/
public class ApiAsync extends AsyncTask<String, Void, String> {
private static final int TIMEOUT_EM_MILISEGUNDOS = 50000;
private static final String METODO_HTTP_GET = "GET";
private static final String METODO_HTTP_POST = "POST";
@Override
protected String doInBackground(String... params) {
String endereco = params[0];
InputStream is = null;
try {
URL url = new URL(endereco);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIMEOUT_EM_MILISEGUNDOS);
conn.setConnectTimeout(TIMEOUT_EM_MILISEGUNDOS);
conn.setRequestMethod(METODO_HTTP_GET);
conn.setDoInput(true);
//Adicionar cabeçalho
//conn.setRequestProperty(HEADER_EMITENTE, emitente);
conn.setChunkedStreamingMode(1024);
conn.connect();
int response = conn.getResponseCode();
is = conn.getInputStream();
return readIt(is);
} catch (Exception ex){
ex.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public String readIt(InputStream stream) throws IOException, UnsupportedEncodingException {
BufferedReader r = new BufferedReader(new InputStreamReader(stream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
return total.toString();
}
}
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
class APi extends ApiAsync{
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Recebido");
builder.setMessage(s);
builder.setCancelable(true);
AlertDialog alerta = builder.create();
alerta.show();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
new APi().execute("http://192.168.0.38:5000/");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment