【发布时间】:2015-04-12 19:39:18
【问题描述】:
我正在尝试通过this 教程向我的服务器发送 http 帖子以检查登录凭据是否有效。我需要向我的服务器发出请求,但我必须添加授权,我从this answer 获取带有函数 getB64Auth 的字符串。该函数记录正确的变量,(与我在邮递员中使用的相同)。但是由于某种原因,如果我运行我的代码,我的程序就会停止运行。我已经尝试从 cmets 添加代码,但没有帮助。
我做错了什么?
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();
}
}
当我运行我的代码时,应用程序停止工作,我可以找到日志验证,但我找不到任何失败成功日志。 我在示例中更改的内容是第 3 步。
我在那里添加了我的授权。
并删除了第 4 步,因为我不需要它。
工作邮递员示例,我想在 android 中提出相同的请求。
你可以看到我得到了响应,并且只根据我的请求设置了授权。
我找不到任何像样的帖子/授权教程,所以我希望我正在寻找正确的方向。
这是一个 android 4.* 项目
【问题讨论】:
-
“应用程序停止工作”是什么意思 - 它只是卡住了还是完全崩溃了?你试过用 Charles / Fiddler 嗅探 Http 流量吗?
-
@SamuilYanovski 应用关闭,消息应用停止
-
您在 LogCat 中是否看到任何可疑的内容(即任何错误)?一个小问题——你已经包括了互联网许可,对吧? :)
-
权限未设置!添加,现在它不会崩溃,但我在控制台中收到以下消息:04-12 13:10:11.905 8426-8426/nl.svenboogaart.frietapp D/win:win1 04-12 13:10:11.905 8426-8426/ nl.mydomain.myapp D/Http Post 响应:﹕ org.apache.http.message.BasicHttpResponse@42491d38 04-12 13:10:11.910 8426-8426/nl.mydomain.myapp I/Choreographer﹕跳过 53 帧!应用程序可能在其主线程上做了太多工作。
-
状态码是 200 所以它成功了!
标签: android post authorization