我发送httppost是正确的吗?我正在检查我的网络服务器上的encodeDauthString,并可以验证该字符串是否正确。不知道为什么我不能认证。
public JSONObject connect(String url) {
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpPost httppost = new HttpPost(url);
String authString = usernameEditText.getText().toString() + ":" + passwordEditText.getText().toString();
String encodedAuthString = Base64.encodeToString(authString.getBytes(),Base64.DEFAULT);
String finalAuthString = "Basic " + encodedAuthString;
// Execute the request
HttpResponse response;
try {
httppost.addHeader("Authorization", finalAuthString);
response = httpclient.execute(httppost);
// Examine the response status
Log.i("Praeda", response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
// A Simple JSONObject Creation
JSONObject json = new JSONObject(result);
// Closing the input stream will trigger connection release
instream.close();
return json;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected JSONObject doInBackground(String... urls) {
return connect(urls[0]);
}
@Override
protected void onPostExecute(JSONObject json) {
String authorized = "200";
String unauthorized = "401";
String notfound = "404";
String status = new String();
try {
// Get the messages array
JSONObject response = json.getJSONObject("response");
status = response.getString("status");
if(status.equals(authorized))
Toast.makeText(getApplicationContext(), "Authorized",Toast.LENGTH_SHORT).show();
else if (status.equals(unauthorized))
Toast.makeText(getApplicationContext(), "Unauthorized",Toast.LENGTH_SHORT).show();
else if(status.equals(notfound))
Toast.makeText(getApplicationContext(), "Not found",Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
System.out.println(e);
} catch (NullPointerException e) {
System.out.println(e);
}
}
}
更新:
当我硬编码编码的字符串时,一切都很好。
当我使用base64编码器时,得到的结果与编码字符串相同,但服务器返回401。
最佳答案
您没有在此代码中设置任何标题。使用setHeader()
设置标题。httpclient的documentation中也包含了这一点,来自previous question的信息也是如此。
Here is a sample project设置授权头。注意,它使用一个单独的base64编码器,因为内置编码器只在android 2.2,iirc中出现。