Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Created by Antonio on 26/02/2016.
- */
- public class Server {
- private static final int CONNECTION_TIMEOUT = 10000;
- private static final int DATARETRIEVAL_TIMEOUT = 10000;
- private static final String SERVER_URL = "http://www.techtalents.info/login_app.php";
- private static String sessionID;
- private static String requestUrl(String url, String postParameters) {
- HttpURLConnection urlConnection = null;
- try {
- URL urlToRequest = new URL(url);
- urlConnection = (HttpURLConnection) urlToRequest.openConnection();
- urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
- urlConnection.setReadTimeout(DATARETRIEVAL_TIMEOUT);
- if (postParameters != null) {
- urlConnection.setDoOutput(true);
- urlConnection.setRequestMethod("POST");
- urlConnection.setFixedLengthStreamingMode(
- postParameters.getBytes().length);
- urlConnection.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded;charset=UTF-8");
- PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
- out.print(postParameters);
- out.close();
- }
- int statusCode = urlConnection.getResponseCode();
- if (statusCode != HttpURLConnection.HTTP_OK) {
- }
- InputStream in =
- new BufferedInputStream(urlConnection.getInputStream());
- String respuesta = getResponseText(in);
- return respuesta;
- } catch (MalformedURLException e) {
- } catch (SocketTimeoutException e) {
- } catch (IOException e) {
- } finally {
- if (urlConnection != null) {
- urlConnection.disconnect();
- }
- }
- return null;
- }
- private static String getResponseText(InputStream in) {
- try {
- Reader reader = new InputStreamReader(in, "UTF-8");
- char[]tamanio=new char[6];
- reader.read(tamanio);
- int tam = Integer.parseInt(new String(tamanio));
- char[] buffer = new char[tam];
- reader.read(buffer);
- return new String(buffer);
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return "";
- }
- public static boolean login(String username, String password) {
- String response = requestUrl(SERVER_URL, "username="+username+"&password="+password);
- if(response != null && response.startsWith("OK")){
- sessionID = response.substring(2);
- return true;
- }
- sessionID=null;
- return false;
- }
- public static String post(ArrayList<String> parametros){
- StringBuilder sb = new StringBuilder();
- if(sessionID == null){
- return null;
- }
- sb.append("sess_id=" + sessionID);
- for(int i=0;i<parametros.size();i++){
- sb.append("&" + parametros.get(i));
- }
- String response = requestUrl(SERVER_URL, sb.toString());
- Log.i("SERVER:",response);
- return response;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement