Android帖子授权

时间:2015-04-09 23:41:54

标签: android post authorization

我正在尝试向我的服务器发送http帖子,以便在this教程的帮助下检查登录凭据是否有效。我需要向我的服务器发出请求,但我必须添加Authorization,我从this answer获取带有函数getB64Auth的字符串。该函数记录正确的变量,(与我用邮递员一样)。但由于某些原因,如果我运行我的代码,我的程序将停止运行。我已经尝试添加评论中的代码,但它没有帮助。

我做错了什么?

private String getB64Auth (String login, String pass) {
    String source=login+":"+pass;
    String ret="Basic "+Base64.encodeToString(source.getBytes(),Base64.URL_SAFE| Base64.NO_WRAP);
    Log.d("authy", ret);
    return ret;
}


/** Called when the user clicks the Login button */
public void login(View view) {

    // Getting username and password
    EditText userText = (EditText) findViewById(R.id.inputLoginUsername);
    EditText passText = (EditText) findViewById(R.id.inputLoginPassword);
    String usernameInput =  userText.getText().toString();
    String passwordInput = passText.getText().toString();

    String authorizationString = getB64Auth(usernameInput,passwordInput );

    // Do something in response to button
    // 1. Create an object of HttpClient
    HttpClient httpClient = new DefaultHttpClient();
    // 2. Create an object of HttpPost

    // I have my real server name down here
    HttpPost httpPost = new HttpPost("https://myservername.com/login");
    // 3. Add POST parameters

    httpPost.setHeader("Authorization", authorizationString);






    // 5. Finally making an HTTP POST request

    try {
        HttpResponse response = httpClient.execute(httpPost);
        Log.d("win", "win1");
        // write response to log
        Log.d("Http Post Response:", response.toString());
    } catch (ClientProtocolException e) {
        Log.d("fail", "Fail 3");
        // Log exception
        e.printStackTrace();
    } catch (IOException e) {
        Log.d("fail", "Fail 4");
        // Log exception
        e.printStackTrace();
    }
}    

当我运行我的代码时,应用程序停止工作,我可以找到日志authy但我无法找到任何失败的成功日志。 我在示例中更改的内容是第3步。

我在那里添加了我的授权。

并删除了第4步因为我不需要它。

工作邮递员示例,我希望在Android中提出相同的请求。

enter image description here 您可以看到我收到回复,并且只根据我的请求设置了授权。

我找不到任何体面的帖子/授权教程,所以我希望我正在寻找正确的方向。

这是一个android 4. *项目

1 个答案:

答案 0 :(得分:2)

关于此类问题的一些建议:

  • 检查权限(INTERNET是您需要的权限)
  • Charles / Fiddler等应用可让您从设备中嗅探Http流量,以便调查发送的内容
  • 如果应用程序崩溃 - 请检查LogCat消息(例如,它可能包含一条消息,说明缺少哪个权限)

关于此消息:

  

应用程序可能在其主线程上做了太多工作。

这通常意味着您在主线程中执行了一些繁重的操作 - 例如从Http响应中解析Json。通常,您希望在后台线程中执行所有这些操作,并使用主操作仅更新UI。