0

I'm new to android programming, and I wanted to make a small program to download strings from a specific API-URL. (I'm not new to the programming overall).

Now I'm stuck with the following code, just to download my string from url:

String urlToDownloadToken = baseUrl + "?action=login&username=xxx&password=xxx";
Object taskResult = new DownloadString().execute(urlToDownloadToken);

The implementation of the download class is as following. In the callbnack function I have a toast that should theoretically display the Data, but it always makes an emty toast (The code I have found is from here: https://stackoverflow.com/a/14418213):

Edit: Full source after applying recommendation to use OkHttp

public class MusicScroll extends AppCompatActivity {

String baseUrl = "http://ppcinj.com";
String token = "";

AlertDialog.Builder dlgAlert;

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

    //Set MessageBox properties...
    dlgAlert = new AlertDialog.Builder(this);
    dlgAlert.setCancelable(true);
    dlgAlert.setTitle("Message from Application");
    dlgAlert.setPositiveButton("OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            });

    try {
        String urlToDownloadToken = baseUrl + "?action=login&username=xxx&password=xxx";
        token = downloadString(urlToDownloadToken);
    } catch (Exception e) {
        dlgAlert.setMessage("Error downloading data: " + e.getMessage());
        dlgAlert.create().show();
    }

    dlgAlert.setMessage(token);
    dlgAlert.create().show();
}

OkHttpClient client = new OkHttpClient();

String downloadString(String url) throws IOException {
    Request request = new Request.Builder()
            .url(url)
            .build();

    Response response = client.newCall(request).execute();
    return response.body().string();
}

} Is there any way I could download as simple as with C#'s WebClient?

Kind regards :)

Edit 2: Got it to work with the following code :)

public class MusicScroll extends AppCompatActivity {

String baseUrl = "http://ppcinj.tk:5656";
String token = "";

AlertDialog.Builder dlgAlert;

Handler mHandler = new Handler(Looper.getMainLooper()) {
    @Override
    public void handleMessage(Message message) {
        if (message.what == 1) {
            Toast.makeText(getApplicationContext(), token, Toast.LENGTH_LONG).show();
        }
    }
};

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

    //Set MessageBox properties...
    dlgAlert = new AlertDialog.Builder(this);
    dlgAlert.setCancelable(true);
    dlgAlert.setTitle("Message from Application");
    dlgAlert.setPositiveButton("OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            });

    try {
        String urlToDownloadToken = baseUrl + "?action=login&username=michael&password=qwerty123";

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(urlToDownloadToken)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.e("BNK", e.toString());
            }

            @Override
            public void onResponse(Response response) throws IOException {
                Log.i("BNK", response.toString());
                token = response.body().string();
                Message msg = mHandler.obtainMessage(1);
                msg.sendToTarget();
            }
        });
    } catch (Exception e) {
        dlgAlert.setMessage("Error downloading data: " + e.getMessage());
        dlgAlert.create().show();
    }
}

public void showToken()
{
    Toast.makeText(getApplicationContext(), token, Toast.LENGTH_LONG).show();
}

}

Community
  • 1
  • 1

2 Answers2

1

HttpClient has been deprecated for years and has been removed from Android 6. You should use OkHttp instead, it's the new standard. And it is a lot easier :).

Barend
  • 17,296
  • 2
  • 61
  • 80
0

You can refer to the following sample code:

public class MainActivity extends AppCompatActivity {        
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);            
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url("http://ppcinj.com?action=login&username=michael&password=qwerty123")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {                    
                Log.e("BNK", e.toString());
            }

            @Override
            public void onResponse(Response response) throws IOException {                    
                Log.i("BNK", response.toString());
            }
        });
    }
}

Here is the screenshot of logcat

BNK's screenshot

Hope this helps!

BNK
  • 23,994
  • 8
  • 77
  • 87
  • Okay, i have implemented it like this, but it still doesn't work. In the logcat i see the line you have pointed me to, but the response is still empty :(. – Michael Salivon Oct 26 '15 at 16:31
  • So, which response do you expect to get? The token? – BNK Oct 26 '15 at 22:23
  • Because you did not provide the correct credentials so if using `http://ppcinj.com?action=login&username=michael&password=qwerty123` then the server responsed a HTML page. You can use Postman to test first – BNK Oct 27 '15 at 01:25
  • From your edit, looks like that your issue has been solved, right? – BNK Oct 27 '15 at 10:16