Perform HTTP Requests over USB and Sockets

0

I am working on a development which consists of being able to make HTTP requests using the usb cable and the pc as an intermediary, I followed this page which helped me but I'm having a little problem which I can not fix, here's my code:

I have my LoginActivity.java class, in which I perform the initialization of the socket and also the login.

public class LoginActivity extends AppCompatActivity {

private boolean isChekedOffLine = false;

private Handler handler = new Handler();
private ServerSocket serverSocket;
private int SERVERPORT;
private int TIMEOUT_SERVER;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    initUI();        

    SERVERPORT = Parameters.SERVER_PORT;
    TIMEOUT_SERVER = Parameters.SERVER_TIMEOUT;

    Thread fst = new Thread(new ServerThread());
    fst.start();
}

private void initUI() {
    String userLogin = null;        
    ....
    ....

    final Button btnAccess = (Button) findViewById(R.id.btnAccess);                
    btnAccess.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Login loginBean = new Login();
            String user = txtUser.getText().toString().trim();
            String pass = txtPass.getText().toString().trim();
            if (!user.equals("")){
                if(!pass.equals("")){
                    loginBean.setUser(user.toUpperCase());
                    loginBean.setPass(pass);
                    loginBean.setType("A");
                    loginBean.setIsOffline(isChekedOffLine);
                }else {
                    txtPass.setError(getString(R.string.err_pass));
                    return;
                }
            }else {
                txtUser.setError(getString(R.string.err_user));
                return;
            }
            LoginTask loginTask = new LoginTask(LoginActivity.this, loginBean);
            loginTask.execute();
        }
    });        

public class ServerThread implements Runnable {
    public void run() {
        Socket client = null;
        try {
            serverSocket = new ServerSocket(SERVERPORT);
            serverSocket.setSoTimeout(TIMEOUT_SERVER);

            client = serverSocket.accept();
            Globals.socketIn = new BufferedReader(new InputStreamReader(client.getInputStream()));
            Globals.socketOut = new PrintWriter(client.getOutputStream(),true);

        }catch (SocketTimeoutException e){
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(LoginActivity.this,"Tiempo de espera terminado",Toast.LENGTH_SHORT).show();
                }
            });
        }catch (IOException e) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(LoginActivity.this,"Ocurrio un error al inicia el servicio",Toast.LENGTH_SHORT).show();
                }
            });
            e.printStackTrace();
        }finally {
            try {
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (IOException e) {
                Log.e("LoginActivity",e.getMessage());
                e.printStackTrace();
            }
        }

        if (client != null) {
            Globals.connected = true;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(LoginActivity.this,"Conexión establecida con exito.!!",Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}

  @Override
  protected void onStop() {
    super.onStop();
    try {
        if (serverSocket != null) {
            serverSocket.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
  }

  public static class Globals {
      public static boolean connected;
      public static BufferedReader socketIn;
      public static PrintWriter socketOut;
  }

}

Then in my class LoginTask.java , to perform the validation send a request HTTP through the getValidateUser () . p>

public class LoginTask extends AsyncTask {

private ProgressDialog progressDialog;
private Context context;
private Resources resources;
private Login loginParams;
private String msgAccess;

public LoginTask(Context context, Login loginParams){
    this.context = context;
    this.resources = context.getResources();
    this.loginParams = loginParams;
}

@Override
protected void onPreExecute(){
    progressDialog = new ProgressDialog(context);
    progressDialog.setMessage(resources.getString(R.string.msg_access));
    progressDialog.setCancelable(true);
    progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    progressDialog.show();
}

@Override
protected String doInBackground(Object[] objects) {        
    msgAccess = getValidateUser();
    return msgAccess;
}

@Override
protected void onPostExecute(Object o){
    if (msgAccess != null) {
        if (msgAccess.equals("OK")) {
            ....
            ....
        } else{
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle(R.string.msg_alert_title_login);
            builder.setMessage(msgAccess);
            builder.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                }
            });
            builder.show();
        }
    }else{
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.msg_alert_title_login);
        builder.setMessage(R.string.err_msg_null);
        builder.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
            }
        });
        builder.show();
    }

    if (progressDialog.isShowing()) {
        progressDialog.dismiss();
    }
}

private String getValidateUser(){        
    String isUser = null;
    String line;
    JSONArray json;
    StringBuilder builder = new StringBuilder();
    StringBuilder requestURL = new StringBuilder();
    URL url;
    URLConnection conn;
    BufferedReader reader;
    try {
        requestURL.append(Parameters.REQUEST_URL_SERVICE_COLLID).append("/").append(loginParams.getUser());
        if (LoginActivity.Globals.connected){
            url = new URL(requestURL.toString());
            conn = url.openConnection();
            conn.setConnectTimeout(Parameters.TIMEOUT);
            conn.setReadTimeout(Parameters.TIMEOUT);
            LoginActivity.Globals.socketOut.println(requestURL.toString());
            LoginActivity.Globals.socketOut.flush();
            // Aqui se queda y tiene al ProcessDialog sin terminar y no puede pasar al método onPostExecute
            while ((line = LoginActivity.Globals.socketIn.readLine()) != null) {                    
                builder.append(line);
            }                
        }else {
            url = new URL(requestURL.toString());
            conn = url.openConnection();
            conn.setConnectTimeout(Parameters.TIMEOUT);
            conn.setReadTimeout(Parameters.TIMEOUT);
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        }
        if (builder.toString().length() > 2) {
            JSONObject jsonObj = new JSONObject("{\"users\": [" + builder.toString() + "]}");
            json = jsonObj.getJSONArray("users");
            for (int i=0;i<json.length();i++){
                JSONObject responseObject = json.getJSONObject(i);
                if (responseObject != null) {                        
                    ....
                    ....  
                }
            }
        }
    } catch (Exception e) {
        Log.e(tag,e.getMessage());
        e.printStackTrace();
    }
    return isUser;
}
}

The problem is given in the while (commented in the code), since for some reason it remains in an unfinished loop (or finish and remains there), I put the Log to show the lines that are printed and I see that only a single line is shown, which is the one I require but it remains unfinished, possibly something is doing wrong or I'm missing something else.

I hope you explained, Thank you.

    
asked by Brando T. 02.06.2016 в 17:50
source

2 answers

1

@BrandoT check your code if you put the mouse pointer on the line, I can assure that you will have a message like this:

  

Condition '(line = LoginActivity.Globals.socketIn.readLine ())! = null'   is always 'true'

Which indicates that you have an infinite "loop", you can make this change to work properly:

   String line = LoginActivity.Globals.socketIn.readLine();
    while (line != null) {
        builder.append(line);
        line = LoginActivity.Globals.socketIn.readLine();
    }
}
    
answered by 02.06.2016 в 19:16
0

Well, after trying several alternatives I found the solution, or at least the one that works for me. In the while part add the following validation.

String line = LoginActivity.Globals.socketIn.readLine();
while (line != null) {
    Log.e(tag,line);
    builder.append(line);
    if (LoginActivity.Globals.socketIn.ready()){ // Aquí la validación
          line = LoginActivity.Globals.socketIn.readLine();
    }else{
          line = null;
    }
}

I hope it's useful.

    
answered by 02.06.2016 в 23:23