Android 发布数据后从服务器获取Http响应
基本上,我有一个注册表单,用户在其中提示输入电子邮件、用户名和密码。填写此表格后,所有数据通过POST请求传输到数据库。到现在为止,一直都还不错。现在我想从服务器上得到一个回复,比如说你已经注册了,或者这个电子邮件/用户名已经在使用了。{“status”=“…”,“message”=“…”}由PHP在服务器端完成。更清楚地说,我想返回Http响应主体,即“消息”。我所能找到的就是获取“状态”,即状态代码 这是我的密码Android 发布数据后从服务器获取Http响应,android,json,Android,Json,基本上,我有一个注册表单,用户在其中提示输入电子邮件、用户名和密码。填写此表格后,所有数据通过POST请求传输到数据库。到现在为止,一直都还不错。现在我想从服务器上得到一个回复,比如说你已经注册了,或者这个电子邮件/用户名已经在使用了。{“status”=“…”,“message”=“…”}由PHP在服务器端完成。更清楚地说,我想返回Http响应主体,即“消息”。我所能找到的就是获取“状态”,即状态代码 这是我的密码 public class MainActivity extends Acti
public class MainActivity extends ActionBarActivity {
EditText emailText;
EditText usernameText;
EditText passwordText;
Button btn;
User user;
static String locale;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emailText = (EditText) findViewById(R.id.emailText);
usernameText = (EditText) findViewById(R.id.usernameText);
passwordText = (EditText) findViewById(R.id.passwordText);
btn = (Button) findViewById(R.id.button);
final String username = usernameText.getText().toString();
locale = getResources().getConfiguration().locale.getCountry();
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.button:
if(!validate())
Toast.makeText(getBaseContext(), "Enter some
data!", Toast.LENGTH_LONG).show();
// call AsynTask to perform network operation on
separate thread
new HttpAsyncTask().execute("....");
break;
}
}
});
}
public static String POST(String url, User user) {
InputStream inputStream = null;
String result = "";
//Built the object
JSONObject jsonObject = new JSONObject();
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = "";
jsonObject.accumulate("email", user.getEmail());
jsonObject.accumulate("username", user.getUsername());
jsonObject.accumulate("password", user.getPassword());
jsonObject.accumulate("location",locale);
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpClient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
Log.d("testing",inputStream.toString());
Log.d("test", httpResponse.toString());
StatusLine statusLine = httpResponse.getStatusLine();
Log.d("test", httpResponse.toString());
int statusCode = statusLine.getStatusCode();
if(statusCode == 200) {
// 10. convert inputstream to string
if (inputStream != null) {
result = convertInputStreamToString(inputStream);
//String resp_body =
EntityUtils.toString(httpResponse.getEntity());
//Log.d("resp_body", resp_body.toString());
//JSONObject jsobj = new JSONObject(resp_body);
HttpEntity resEntity = httpPost.getEntity();
}else
result = "Did not work!";
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String... urls) {
user = new User();
user.setUsername(usernameText.getText().toString());
user.setPassword(passwordText.getText().toString());
user.setEmail(emailText.getText().toString());
return POST(urls[0],user);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!",
Toast.LENGTH_LONG).show();
Intent i = new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("username",usernameText.getText().toString());
startActivity(i);
}
}
private boolean validate(){
if(usernameText.getText().toString().trim().equals(""))
return false;
else if(passwordText.getText().toString().trim().equals(""))
return false;
else if(emailText.getText().toString().trim().equals(""))
return false;
else
return true;
}
private static String convertInputStreamToString(InputStream
inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new
InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
公共类MainActivity扩展了ActionBarActivity{
编辑文本电子邮件文本;
EditText用户名文本;
编辑文本密码文本;
按钮btn;
用户;
静态字符串区域设置;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emailText=(EditText)findViewById(R.id.emailText);
usernameText=(EditText)findViewById(R.id.usernameText);
passwordText=(EditText)findViewById(R.id.passwordText);
btn=(按钮)findViewById(R.id.Button);
最终字符串username=usernameText.getText().toString();
locale=getResources().getConfiguration().locale.getCountry();
btn.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
开关(v.getId()){
案例R.id按钮:
如果(!validate())
Toast.makeText(getBaseContext(),“输入一些
data!”,Toast.LENGTH_LONG).show();
//调用AsynTask在上执行网络操作
独立线程
新建HttpAsyncTask().execute(“..”);
打破
}
}
});
}
公共静态字符串帖子(字符串url,用户){
InputStream InputStream=null;
字符串结果=”;
//创建对象
JSONObject JSONObject=新的JSONObject();
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
字符串json=“”;
累积(“email”,user.getEmail());
累积(“username”,user.getUsername());
累积(“密码”,user.getPassword());
jsonObject.累加(“位置”,区域设置);
json=jsonObject.toString();
StringEntity se=新的StringEntity(json);
httpPost.setEntity(se);
setHeader(“接受”、“应用程序/json”);
setHeader(“内容类型”、“应用程序/json”);
HttpResponse HttpResponse=httpClient.execute(httpPost);
//9.将响应作为inputStream接收
inputStream=httpResponse.getEntity().getContent();
Log.d(“测试”,inputStream.toString());
Log.d(“test”,httpResponse.toString());
StatusLine StatusLine=httpResponse.getStatusLine();
Log.d(“test”,httpResponse.toString());
int statusCode=statusLine.getStatusCode();
如果(状态代码==200){
//10.将inputstream转换为字符串
如果(inputStream!=null){
结果=convertInputStreamToString(inputStream);
//字符串响应正文=
toString(httpResponse.getEntity());
//Log.d(“resp_body”,resp_body.toString());
//JSONObject jsobj=新的JSONObject(各自主体);
HttpEntity当前性=httpPost.getEntity();
}否则
结果=“不起作用!”;
}
}捕获(例外e){
e、 printStackTrace();
}
返回结果;
}
私有类HttpAsyncTask扩展了AsyncTask
{
@凌驾
受保护的字符串doInBackground(字符串…URL){
user=新用户();
user.setUsername(usernameText.getText().toString());
user.setPassword(passwordText.getText().toString());
user.setEmail(emailText.getText().toString());
返回帖子(URL[0],用户);
}
//onPostExecute显示异步任务的结果。
@凌驾
受保护的void onPostExecute(字符串结果){
Toast.makeText(getBaseContext(),“已发送数据!”,
Toast.LENGTH_LONG).show();
意图i=新意图(MainActivity.this,SecondActivity.class);
i、 putExtra(“用户名”,usernameText.getText().toString());
星触觉(i);
}
}
私有布尔验证(){
if(usernameText.getText().toString().trim().equals(“”)
返回false;
else if(passwordText.getText().toString().trim().equals(“”)
返回false;
else if(emailText.getText().toString().trim().equals(“”)
返回false;
其他的
返回true;
}
私有静态字符串转换器InputStreamToString(InputStream
inputStream)引发IOException{
BufferedReader BufferedReader=新的BufferedReader(新的
InputStreamReader(inputStream));
字符串行=”;
字符串结果=”;
而((line=bufferedReader.readLine())!=null)
结果+=行;
inputStream.close();
返回结果;
}
}
我建议您使用将json发布到服务器。
它是一个Web服务库,简化了android和REST Web服务之间的大量通信。plz显示您的HttpAsyncTask在后台执行的操作,您应该能够在异步调用中获取HTTP响应的内容,并返回消息
convertInputStreamToString()
应该可以工作,并且EntityUtils.toString(httpResponse.getEntity());
也一样。您只需要其中一个。不要同时使用它们。Log.d(“testing”,inputStream.toString());
为什么不告诉我这个语句提供了什么?Log.d(“test”,httpResponse.toString());
。还有这个?result=“Exception:+e.getMessage();
将其添加到POST函数的catch块中。