我需要能够获得android中的http头代码,这将由php代码生成。
我对android很新,并且无法掌握正确的方法。
目前我在signup.java文件上的代码能够将一些数据发布到基于php的webservice,并且根据发送的数据,webservice回显一个json编码的响应。
发生错误时响应的php代码是
$response["error"] = true;
$response["message"] = "Username Already taken";
echoRespnse(400,$response);
成功的代码是
$response["error"] = false;
$response["message"] = "Successfuly Registered";
echoRespnse(201,$response);
这将生成一个json ecoded响应消息。
我的signup.java文件包含以下代码
public void post() throws UnsupportedEncodingException
{
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = null;
HttpPost httppost = new HttpPost("http://www.rgbpallete.in/led/api/signup");
if (password.equals(confirmpass)) {
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("uname", uname));
nameValuePairs.add(new BasicNameValuePair("pass", password));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("phone", phone));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpResponse = httpclient.execute(httppost); //http header response??
//Code to check if user was successfully created
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(getBaseContext(), "Password mismatch", Toast.LENGTH_SHORT).show();
//Reset password fields
pass.setText("");
cpass.setText("");
}
}
我想知道httpResponse
是否会保存由webservice生成的http头响应代码,或者我是否需要解析json响应消息以了解webserivce返回的内容。
答案 0 :(得分:3)
可以通过以下方式检索响应代码:
final int statusCode = httpResponse.getStatusLine().getStatusCode();
switch (statusCode)
{
case 201:
// Successfuly Registered
break;
case 400:
// Username Already taken
break;
default:
break;
}
要列出标题值,您可以使用:
for (final Header h : httpResponse.getAllHeaders())
{
Log.d("Responser Header", h.getName() + ": " + h.getValue()); // or h.getElements()
}
或直接选择所需的标题:
final String[] contentLength = httpResponse.getHeaders("Content-Length");
并解析它。