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

これはうまくいきます!!

   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 に答える