【问题标题】:Https request, authentication in AndroidHttps请求,Android中的认证
【发布时间】:2011-03-06 21:39:32
【问题描述】:

我目前正在尝试通过 http Get 调用向服务器进行身份验证。下面提供的代码在 java 项目中编译时有效。将正确的令牌返回给程序。但是,每当我尝试在 Android 中实现相同的代码时,我都不会通过 Get 调用返回令牌。

在 Android 中,我在函数中返回 inputLine,但 inputLine 始终为空字符串。

system.out.println() 打印返回的令牌。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;

public class JavaHttpsExample 
{

public static void main(String[] args)
{   String inputLine = new String();
    try
    {
    String httpsURL = "https://the url";
    URL myurl = new URL(httpsURL);
    HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
    InputStream ins = con.getInputStream();
    InputStreamReader isr=new InputStreamReader(ins);
    BufferedReader in =new BufferedReader(isr);

    inputLine = in.readLine();

    System.out.println(inputLine);

    in.close();


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

感谢您的帮助!!!

【问题讨论】:

  • 你能看到服务器端发生了什么吗?访问日志、状态码等
  • 很遗憾没有,服务器托管在外面
  • 当我在 Android 中运行代码时,它似乎总是在“InputStream ins - con.getInputStream();”行失败它抛出 IOException。但是,当我将代码作为 java 应用程序运行时,这不会发生。
  • 你能发布堆栈跟踪吗?

标签: java android https get


【解决方案1】:

我正在使用 POST 和 FormEntity 从服务器检索数据(例如身份验证),我从来没有遇到任何问题:

final String httpsURL = "https://the url";
final DefaultHttpClient client = new DefaultHttpClient();
final HttpPost httppost = new HttpPost(httpsURL);

//authentication block:
final List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair("userName", userName));
nvps.add(new BasicNameValuePair("password", password));
final UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps, HTTP.UTF_8);
httppost.setEntity(p_entity);

//sending the request and retrieving the response:
HttpResponse response = client.execute(httppost);
HttpEntity responseEntity = response.getEntity();

//handling the response: responseEntity.getContent() is your InputStream
final InputSource inputSource = new InputSource(responseEntity.getContent());
[...]

也许你会发现这很有用

【讨论】:

【解决方案2】:

您可能没有将 Internet-Permission 添加到您的项目 AndroidManifest.xml。 如果是这样,请将以下行添加为 &lt;manifest/&gt; 节点的子节点:

<uses-permission android:name="android.permission.INTERNET" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2014-10-12
    • 2019-08-16
    • 1970-01-01
    相关资源
    最近更新 更多