带有基本身份验证的 HTTPS 连接结果为“未经授权”

发布于 2024-11-30 11:22:33 字数 2334 浏览 4 评论 0 原文

我正在尝试按照以下方式从我的 Android/Java 源代码访问 Basecamp API ... 。

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class BCActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        DefaultHttpClient httpClient = new DefaultHttpClient();

        //final String url = "https://encrypted.google.com/webhp?hl=en"; //This url works
        final String url = "https://username:[email protected]/people.xml"; //This don't
        HttpGet http = new HttpGet(url);
        http.addHeader("Accept", "application/xml");
        http.addHeader("Content-Type", "application/xml"); 

        try {

            //  HttpResponse response = httpClient.execute(httpPost);
            HttpResponse response = httpClient.execute(http);

            StatusLine statusLine = response.getStatusLine();
            System.out.println("statusLine : "+ statusLine.toString()); 

            ResponseHandler <String> res = new BasicResponseHandler();  

            String strResponse = httpClient.execute(http, res);
            System.out.println("________**_________________________\n"+strResponse);
            System.out.println("\n________**_________________________\n");

        } catch (Exception e) {
            e.printStackTrace(); 
        }

        WebView myWebView = (WebView) this.findViewById(R.id.webView);
        myWebView.loadUrl(url);//Here it works and displays XML response

    }
}

此 URL 在 WebView 中显示响应,但当我尝试通过 HttpClient 访问时显示未经授权的异常,如上所示

这是通过 Android/Java 访问 Basecamp API 的正确方法吗? 或者 请为我提供正确的方法。

I am trying to access Basecamp API from my Android/Java source code following way ....

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class BCActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        DefaultHttpClient httpClient = new DefaultHttpClient();

        //final String url = "https://encrypted.google.com/webhp?hl=en"; //This url works
        final String url = "https://username:[email protected]/people.xml"; //This don't
        HttpGet http = new HttpGet(url);
        http.addHeader("Accept", "application/xml");
        http.addHeader("Content-Type", "application/xml"); 

        try {

            //  HttpResponse response = httpClient.execute(httpPost);
            HttpResponse response = httpClient.execute(http);

            StatusLine statusLine = response.getStatusLine();
            System.out.println("statusLine : "+ statusLine.toString()); 

            ResponseHandler <String> res = new BasicResponseHandler();  

            String strResponse = httpClient.execute(http, res);
            System.out.println("________**_________________________\n"+strResponse);
            System.out.println("\n________**_________________________\n");

        } catch (Exception e) {
            e.printStackTrace(); 
        }

        WebView myWebView = (WebView) this.findViewById(R.id.webView);
        myWebView.loadUrl(url);//Here it works and displays XML response

    }
}

This URL displays the response in WebView, but shows Unauthorized exception when I try to access through HttpClient as shown above.

Is this is right way to access Basecamp API through Android/Java?
or
Please provide me a right way to do so.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

秋叶绚丽 2024-12-07 11:22:33

HttpClient 无法从 URI 获取登录信用。
你必须用指定的方法给他们。

如果您使用 HttpClient 4.x,请查看以下内容:
http://hc.apache.org/httpcomponents-client-ga /tutorial/html/authentication.html

但请注意,如果您不想在 HttpClient 上使用新版本(Android 使用 3.x 版本),您应该查看此处:< br>
http://hc.apache.org/httpclient-3.x/authentication.html

这就是理论,现在我们使用它们:
基本上我们使用HTTP,但如果您想使用HTTPS,则必须编辑以下赋值new HttpHost("www.google.com", 80, "http")new HttpHost("www.google.com", 443, "https")

此外,您必须根据您的问题编辑主机 (www.google.com)。
注意:仅需要完整的限定域名 (FQDN),而不需要完整的 URI。

HttpClient 3.x:

package com.test;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;

public class Test2aActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        try {
            HttpHost targetHost = new HttpHost("www.google.com", 80, "http");

            DefaultHttpClient httpclient = new DefaultHttpClient();
            try {
                // Store the user login
                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                        new UsernamePasswordCredentials("user", "password"));

                // Create request
                // You can also use the full URI http://www.google.com/
                HttpGet httpget = new HttpGet("/");
                // Execute request
                HttpResponse response = httpclient.execute(targetHost, httpget);

                HttpEntity entity = response.getEntity();
                System.out.println(EntityUtils.toString(entity));
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

HttpClient 4.x:

注意: 您将需要来自 Apache 的新 HttpClient,此外您还必须重新排列顺序,即 jar 文件位于 Android 库之前。

package com.test;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;

public class TestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        try {
            HttpHost targetHost = new HttpHost("www.google.com", 80, "http");

            DefaultHttpClient httpclient = new DefaultHttpClient();
            try {
                // Store the user login
                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                        new UsernamePasswordCredentials("user", "password"));

                // Create AuthCache instance
                AuthCache authCache = new BasicAuthCache();
                // Generate BASIC scheme object and add it to the local
                // auth cache
                BasicScheme basicAuth = new BasicScheme();
                authCache.put(targetHost, basicAuth);

                // Add AuthCache to the execution context
                BasicHttpContext localcontext = new BasicHttpContext();
                localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

                // Create request
                // You can also use the full URI http://www.google.com/
                HttpGet httpget = new HttpGet("/");
                // Execute request
                HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);

                HttpEntity entity = response.getEntity();
                System.out.println(EntityUtils.toString(entity));
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The HttpClient can't take the login creditals from the URI.
You have to give them with specified methods.

If you use HttpClient 4.x have a look on this:
http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html

But notice if you don't want to use the new version on the HttpClient (Android uses version 3.x), you should look here:
http://hc.apache.org/httpclient-3.x/authentication.html

That was the theory, now we use them:
Basically we use HTTP, but if you want to use HTTPS, you have to edit the following assignment new HttpHost("www.google.com", 80, "http") into new HttpHost("www.google.com", 443, "https").

Furthermore you have to edit the host (www.google.com) for your concerns.
Notice: Only the full qualified domain name (FQDN) is needed not the full URI.

HttpClient 3.x:

package com.test;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;

public class Test2aActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        try {
            HttpHost targetHost = new HttpHost("www.google.com", 80, "http");

            DefaultHttpClient httpclient = new DefaultHttpClient();
            try {
                // Store the user login
                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                        new UsernamePasswordCredentials("user", "password"));

                // Create request
                // You can also use the full URI http://www.google.com/
                HttpGet httpget = new HttpGet("/");
                // Execute request
                HttpResponse response = httpclient.execute(targetHost, httpget);

                HttpEntity entity = response.getEntity();
                System.out.println(EntityUtils.toString(entity));
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

HttpClient 4.x:

Attention: You will need the new HttpClient from Apache and additionally you must rearrange the order, that the jar-file is before the Android library.

package com.test;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;

public class TestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        try {
            HttpHost targetHost = new HttpHost("www.google.com", 80, "http");

            DefaultHttpClient httpclient = new DefaultHttpClient();
            try {
                // Store the user login
                httpclient.getCredentialsProvider().setCredentials(
                        new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                        new UsernamePasswordCredentials("user", "password"));

                // Create AuthCache instance
                AuthCache authCache = new BasicAuthCache();
                // Generate BASIC scheme object and add it to the local
                // auth cache
                BasicScheme basicAuth = new BasicScheme();
                authCache.put(targetHost, basicAuth);

                // Add AuthCache to the execution context
                BasicHttpContext localcontext = new BasicHttpContext();
                localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

                // Create request
                // You can also use the full URI http://www.google.com/
                HttpGet httpget = new HttpGet("/");
                // Execute request
                HttpResponse response = httpclient.execute(targetHost, httpget, localcontext);

                HttpEntity entity = response.getEntity();
                System.out.println(EntityUtils.toString(entity));
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
や三分注定 2024-12-07 11:22:33

最后我明白了如何粘合上面答案中显示的代码...

public static void performPost(String getUri, String xml) {

    String serverName = "*******";
    String username = "*******";
    String password = "********";
    String strResponse = null;

    try {
        HttpHost targetHost = new HttpHost(serverName, 443, "https");

        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            // Store the user login
            httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                    new UsernamePasswordCredentials(username, password));

            // Create AuthCache instance
            AuthCache authCache = new BasicAuthCache();
            // Generate BASIC scheme object and add it to the local
            // auth cache
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(targetHost, basicAuth);

            // Add AuthCache to the execution context
            BasicHttpContext localcontext = new BasicHttpContext();
            localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

            // Create request
            // You can also use the full URI http://www.google.com/
            HttpPost httppost = new HttpPost(getUri);
            StringEntity se = new StringEntity(xml,HTTP.UTF_8);
            se.setContentType("text/xml");
            httppost.setEntity(se); 
            // Execute request
            HttpResponse response = httpclient.execute(targetHost, httppost, localcontext);

            HttpEntity entity = response.getEntity();
            strResponse = EntityUtils.toString(entity);

            StatusLine statusLine = response.getStatusLine();
            Log.i(TAG +": Post","statusLine : "+ statusLine.toString()); 
            Log.i(TAG +": Post","________**_________________________\n"+strResponse);
            Log.i(TAG +": Post","\n________**_________________________\n");

        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

一件非常重要的事情应该如何安排您的库以及您将需要哪些库...

在此处输入图像描述

来自 在这里你会找到这个库。

要在 eclipse 中添加它们(Android sdk < 16 以下)...

Project properties -> java build path -> Libraries -> Add external JARs

要在 eclipse 中按顺序排列它们...

Project properties -> java build path -> order and export

对于 Android sdk >= 16 以上,您必须将这些库放入“libs”文件夹中。

Finally I got it How to glue the code shown in above answer ...

public static void performPost(String getUri, String xml) {

    String serverName = "*******";
    String username = "*******";
    String password = "********";
    String strResponse = null;

    try {
        HttpHost targetHost = new HttpHost(serverName, 443, "https");

        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            // Store the user login
            httpclient.getCredentialsProvider().setCredentials(
                    new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                    new UsernamePasswordCredentials(username, password));

            // Create AuthCache instance
            AuthCache authCache = new BasicAuthCache();
            // Generate BASIC scheme object and add it to the local
            // auth cache
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(targetHost, basicAuth);

            // Add AuthCache to the execution context
            BasicHttpContext localcontext = new BasicHttpContext();
            localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

            // Create request
            // You can also use the full URI http://www.google.com/
            HttpPost httppost = new HttpPost(getUri);
            StringEntity se = new StringEntity(xml,HTTP.UTF_8);
            se.setContentType("text/xml");
            httppost.setEntity(se); 
            // Execute request
            HttpResponse response = httpclient.execute(targetHost, httppost, localcontext);

            HttpEntity entity = response.getEntity();
            strResponse = EntityUtils.toString(entity);

            StatusLine statusLine = response.getStatusLine();
            Log.i(TAG +": Post","statusLine : "+ statusLine.toString()); 
            Log.i(TAG +": Post","________**_________________________\n"+strResponse);
            Log.i(TAG +": Post","\n________**_________________________\n");

        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

One very important thing How your library should be arranged and which libraries you will required ...

enter image description here

From Here you will find this libraries.

To add them in eclipse (Below Android sdk < 16)...

Project properties -> java build path -> Libraries -> Add external JARs

To arrange them in order in eclipse ...

Project properties -> java build path -> order and export

For above Android sdk >= 16 you will have to put these libraries into "libs" folder.

稳稳的幸福 2024-12-07 11:22:33

附录关于 CSchulz 的精彩且非常有用的答案:

在 http 客户端 4.3 中,此:

localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

不再工作(ClientContext.AUTH_CACHE 已弃用)

使用:

import org.apache.http.client.protocol.HttpClientContext;

localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);

参见 http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/protocol/ClientContext.html

和:

http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/protocol/HttpClientContext.html

Appendix on the brilliant and very helpfull answer of CSchulz:

in http client 4.3 this:

localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

does not work anymore (ClientContext.AUTH_CACHE is deprecated)

use:

import org.apache.http.client.protocol.HttpClientContext;

and

localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);

see http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/protocol/ClientContext.html

and:

http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/protocol/HttpClientContext.html

绿阴红影里的.如风往事 2024-12-07 11:22:33

如果您喜欢使用其他答案中提到的 HttpClient 4.x,您也可以
使用 httpclientandroidlib。这是一个转换后的普通 HttpClient,没有 apache.commons
并支持 Android LogCat。

If you like to use the HttpClient 4.x as mentioned in the other answers you could also
use httpclientandroidlib. This is a converted stock HttpClient without apache.commons
and with Android LogCat support.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文