Android httpClient服务器身份验证

时间:2013-07-30 10:43:21

标签: android http authentication

我正在制作一个Android应用程序,它从带有编码JSON的网页中检索数据。当我在网络浏览器中访问该页面时,它会要求我输入服务器身份验证,我输入用户名和密码。当我做一个httpPost时,我该如何做到这一点;它会发送一个用户名和密码,以便我可以访问该页面。

这种认证http://www.wpwhitesecurity.com/wp-content/uploads/2012/08/web-server-authentication-dialogue-box.png

我该怎么做?这是我的代码:

            DefaultHttpClient httpClient = new DefaultHttpClient();


        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpPost);
        } catch (ClientProtocolException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (IOException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        HttpEntity httpEntity = httpResponse.getEntity();
        try {
            is = httpEntity.getContent();
        } catch (IllegalStateException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

3 个答案:

答案 0 :(得分:0)

您可以像这样发送您的用户名和密码:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair(your_username_key_string, your_username));
nameValuePairs.add(new BasicNameValuePair(your_password_key_string, your_password));            

HttpPost oHttpPost = new HttpPost(your_server_url);
oHttpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

答案 1 :(得分:0)

好的......所以你可以通过:

DefaultHttpClient httpClient = new DefaultHttpClient();

String url = "yoururl"+"username="+YourUsername+"password="+Your Paasword;

    HttpPost httpPost = new HttpPost(url);

    HttpResponse httpResponse = null;
    try {
        httpResponse = httpClient.execute(httpPost);
    } catch (ClientProtocolException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    } catch (IOException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }
    HttpEntity httpEntity = httpResponse.getEntity();
    try {
        is = httpEntity.getContent();
    } catch (IllegalStateException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

答案 2 :(得分:0)

将您的参数添加到帖子中:

final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));  
nameValuePairs.add(new BasicNameValuePair("password", password));  
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));

这假设您的登录表单如下:

input type="text" name="username"
input type="password" name="password"