0

I want to make a request with an authentification on an android application with api level 4, HttpClient and httpGet.

    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    String responseString = null;

    try {
        HttpGet httpGet = new HttpGet(uri);
        httpGet.addHeader("referer","http://url.com");
        response = httpclient.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();
        } else {
            response.getEntity().getContent().close();
        }
    } catch (Exception e) {
        return null;
    }

    return responseString;

I test various solution it doesn't work ! maybe I'm doing it wrong ! On IOS it's not very secure but it work with : login:pass@url.com

floflo41
  • 75
  • 3
  • 13

2 Answers2

0
http://www.vogella.com/blog/2012/02/22/android-strictmode-networkonmainthreadexception/

choose asynk tasks or you can choose this way also giving above

Rohit
  • 3,401
  • 4
  • 33
  • 60
0

This it work !!

   DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    String responseString = null;


    String username = "username";
    String password = "password";
    String host = "url.com";
    String ur = uri[0];


    try {
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(host, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password));
        HttpGet httpGet = new HttpGet(uri[0]);
        httpGet.addHeader("referer","http://curl.com");
        response = httpclient.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            Logger.e(out.toString());
            responseString = out.toString();
        } else {
            response.getEntity().getContent().close();
        }
    } catch (Exception e) {
        return null;
    }

    return responseString;
floflo41
  • 75
  • 3
  • 13