0

我想在具有 api 级别 4、HttpClient 和 httpGet 的 android 应用程序上发出一个带有身份验证的请求。

    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;

我测试了各种解决方案,它不起作用!也许我做错了!在 IOS 上它不是很安全,但它适用于:login:pass@url.com

4

2 回答 2

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

选择异步任务,或者你可以选择这种方式也给上面

于 2013-04-15T12:29:14.540 回答
0

这行得通!

   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;
于 2013-04-16T13:22:53.093 回答