如何在Android中将php echo读入字符串?
Posted
技术标签:
【中文标题】如何在Android中将php echo读入字符串?【英文标题】:How to read the php echo into string in Android? 【发布时间】:2014-07-02 10:26:02 【问题描述】:我想获得成功或失败的回显响应。
如果用户登录到页面,如果用户名在数据库中不匹配,则不应允许用户登录并显示一些失败消息。
MainActivity 类
public class MainActivity extends Activity implements OnClickListener
EditText name,number;
Button login;
SetContact contact;
Boolean isInternetPresent = false;
ConnectionDetector cd;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.contact);
cd = new ConnectionDetector(getApplicationContext());
name = (EditText) findViewById(R.id.etname);
number = (EditText) findViewById(R.id.etnumber);
login = (Button) findViewById(R.id.login);
login.setOnClickListener(this);
public static String POST(String url, SetContact contact)
InputStream inputStream = null;
String result = "";
try
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = "";
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", contact.getName());
jsonObject.accumulate("number", contact.getNumber());
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);
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
catch (Exception e)
Log.d("InputStream", e.getLocalizedMessage());
return result;
public void onClick(View view)
String username = name.getText().toString();
String password = number.getText().toString();
/* if(username.equals("name") && password.equals("number"))
Toast.makeText(getBaseContext(), "Username and password incorrect", Toast.LENGTH_LONG).show();
*/
/*else
Toast.makeText(getBaseContext(), "Username does not exist. Please register.", Toast.LENGTH_LONG).show();
*/
switch(view.getId())
case R.id.login:
if(!validate())
Toast.makeText(getBaseContext(), "Please Enter Valid data!", Toast.LENGTH_LONG).show();
else
new HttpAsyncTask().execute("myurl?name="+username+"&number="+password);
break;
private class HttpAsyncTask extends AsyncTask<String, Void, String>
@Override
protected String doInBackground(String... urls)
contact = new SetContact();
contact.setName(name.getText().toString());
contact.setNumber(number.getText().toString());
return POST(urls[0],contact);
protected void onPostExecute(String result)
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent)
Toast.makeText(getBaseContext(), "Thanks for the Mail, We will Reply you soon", Toast.LENGTH_LONG).show();
name.setText("");
number.setText("");
Intent in = new Intent(getApplicationContext(), Updates.class);
startActivity(in);
else
showAlertDialog(MainActivity.this, "No Internet Connection", "Please Connect Internet.", false);
private boolean validate()
if(name.length() > 25)
Toast.makeText(getApplicationContext(), "pls enter less the 25 characher in user name", Toast.LENGTH_SHORT).show();
return true;
else if(name.length() == 0 || number.length() == 0 )
Toast.makeText(getApplicationContext(), "pls fill the empty fields", Toast.LENGTH_SHORT).show();
return false;
else if(number.length() < 6 || number.length() > 13)
number.setError("Not Valid Phone Number");
return false;
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;
@SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status)
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setIcon((status) ? R.drawable.fail : R.drawable.fail);
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialog, int which)
);
alertDialog.show();
【问题讨论】:
你的问题很笼统,请解释一下,你是如何执行http请求的,你是如何使用/运行php站点的。 【参考方案1】:试试这个
HttpResponse response = client.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity());
提示:我在 php 中使用 Print 而不是 echo
【讨论】:
您尝试过打印吗?它对我来说工作正常,并且在 print 中传递 json 值 我用 print 替换并检查了,但它显示感谢消息并显示欢迎。即使对于无效用户,它也在登录【参考方案2】:你的问题很笼统,所以我的回答也是。您可以在PHP
中生成输出,例如通过echo
就像“登录失败”并在android
方面对其进行评估。更好的是,您可以在登录后使用HTTP
状态码来暗示成功或失败(如未授权/401)(PHP side/Android side)。
由于您没有代码,实际上是通过GET
请求进行登录,您应该阅读如何执行this。
【讨论】:
我可以指导您编写该代码,但我想完成您的全部工作。因此,请发布代码草稿,例如基于我帖子中的链接,我们可以一起解决...我帖子中的最后一个链接几乎解决了您在 Android 方面的问题【参考方案3】:您应该使用 JSON 而不是字符串。
我使用 JsonSimple 库将其解析为对象。
这是我的代码示例:
HashMap<String, String> urlParams = new HashMap<String, String>();
urlParams.put("KEY", Value);
String result = "-1";
try
result = rest.POST(host, "Response.php", this.header,
urlParams, 3000);
catch (URISyntaxException e)
// TODO Auto-generated catch block
e.printStackTrace();
JSONObject json = new JSONObject();
try
json = (JSONObject) new JSONParser().parse(result);
return json.get("value_you_want").toString();
catch (ParseException e)
return ("Error parsing " + e.getMessage());
【讨论】:
以上是关于如何在Android中将php echo读入字符串?的主要内容,如果未能解决你的问题,请参考以下文章