Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何从Android应用程序发送特定字符串并将该字符串发布到网站?_Php_Android_Mysql_String_Web - Fatal编程技术网

Php 如何从Android应用程序发送特定字符串并将该字符串发布到网站?

Php 如何从Android应用程序发送特定字符串并将该字符串发布到网站?,php,android,mysql,string,web,Php,Android,Mysql,String,Web,我是android开发的新手,我正在尝试为一个班级项目制作一个android应用程序,让用户点餐。一旦他们点击checkout按钮,就会有一个字符串值包含用户的订单信息,即-鸡肉三明治,西红柿,生菜,蛋黄酱,特别说明,总计:$5.99,将传递给下一个活动。但是,我也希望将此信息从应用程序发送到网站,以便查看网页的人可以看到订单信息。最好的办法是什么 我大致了解了如何使用MySQL和phpmyadmin处理用户登录/注册,但我不确定对这个特定字符串再次这样做是否是显示食物顺序的最佳方式。我不想专门

我是android开发的新手,我正在尝试为一个班级项目制作一个android应用程序,让用户点餐。一旦他们点击checkout按钮,就会有一个字符串值包含用户的订单信息,即-鸡肉三明治,西红柿,生菜,蛋黄酱,特别说明,总计:$5.99,将传递给下一个活动。但是,我也希望将此信息从应用程序发送到网站,以便查看网页的人可以看到订单信息。最好的办法是什么

我大致了解了如何使用MySQL和phpmyadmin处理用户登录/注册,但我不确定对这个特定字符串再次这样做是否是显示食物顺序的最佳方式。我不想专门为一个字符串创建数据库。相反,我只想在网页上发布订单信息,以便工作人员可以查看订单信息并开始处理食品订单

我从这篇文章中找到了一些信息:

以下是根据我在那篇文章中的发现,我迄今为止所做的尝试: 订单列表活动:

@Override
public void onClick(View v) {
    Intent myIntent = null;
    switch (v.getId()) {
        case R.id.checkout:
            if (MainActivity.amountBalance - orderPrice < 0) {
                Toast.makeText(Orderlist.this, "Insufficient balance!", Toast.LENGTH_SHORT).show();
            } else {
                MainActivity.amountBalance = MainActivity.amountBalance - orderPrice;
                myIntent = new Intent(Orderlist.this, OrderPlaced.class);
                Toast.makeText(getApplicationContext(),"Your order was placed!",Toast.LENGTH_LONG).show();
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://mywebsitename.com/mypage.php");
                try {
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);

                    nameValuePairs.add(new BasicNameValuePair("orderinfo", "Chicken sandwich: tomatoes, onions, cheese.\nTotal: $5.99."));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    httpclient.execute(httppost);

                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                }
                startActivity(i);
            }
            break;
        case R.id.cancel:
            i = new Intent(Orderlist.this, MainActivity.class);
            Toast.makeText(Orderlist.this, "All items have been removed from cart.", Toast.LENGTH_LONG).show();
            startActivity(i);
            break;


    }
}
-错误似乎来自Orderlist.java:192,这是下面的一段代码:

 nameValuePairs.add(new BasicNameValuePair("orderinfo", "Chicken sandwich: 
 tomatoes, onions, cheese.\nTotal: $5.99."));
 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
 httpclient.execute(httppost); //ERROR FROM HERE

谢谢大家!

您应该阅读有关Restful Web服务的内容。Android向server.server.NETMVC、SpringMVC、PHP发送带有Jsonor XML字符串数据的Http请求(可选)。。。接收该请求,用业务逻辑处理它,更新数据库并将Json字符串结果返回给Android。登录成功后,服务器必须向移动设备发送令牌,android存储该令牌以验证下一个请求。在您的例子中,您可以使用Http请求POST,将Json数据从android发布到服务器。为了更灵活,您可以使用DTO与Flexjson或Gson库一起序列化数据。您想知道如何做到这一点,请参阅下面的代码

public static String httpPost(String domain, String root, String body,
        String token, String username)
{
    String urlString = "http://"+domain+"/"+root;

    Log.d("httpPost-url",
            " url:"+urlString+
            " ,token:"+token+
            " ,httpPost-body:"+ body+
            " ,username:"+username);

    StringBuffer response = new StringBuffer();
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        if(token!=null)
        {
            conn.setRequestProperty("Authorization", "Basic " + token);
        }
        if(username!=null)
        {
            conn.setRequestProperty("Username", username);
        }
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(body);
        writer.flush();
        BufferedReader br = null;
        try
        {
            Log.d("HttpUtil", "Http code:" + conn.getResponseCode());

            br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        }
        catch (IOException e)
        {
            e.printStackTrace();
            br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
        }
        String inputLine;
        while ((inputLine = br.readLine()) != null)
        {
            response.append(inputLine);
        }
        System.out.println("result from server:"+response.toString());
        conn.disconnect();

    }
    catch (Exception e)
    {
        e.printStackTrace();
        return null;
    }
    return  response.toString();
}


public static String httpGet(String domain, String urlRoot, String token,
                             String username)
{
    String urlString = "http://"+domain+"/"+urlRoot;
    Log.d("httpGet-url:",
            " url:"+urlString+
            " ,token:"+token+
            " ,username:"+username);
    StringBuffer response = new StringBuffer();
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json");
        if(token!=null)
        {
            conn.setRequestProperty("Authorization", "Basic " + token);
        }
        if(username!=null)
        {
            conn.setRequestProperty("Username", username);
        }
        Log.d("HttpUtil","Http code:"+conn.getResponseCode());

        BufferedReader br=null;

        if(conn.getResponseCode()>=200&&conn.getResponseCode()<300) {
            br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        }
        else if(conn.getResponseCode()>=400)
        {
            br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
        }

        String inputLine;
        while ((inputLine = br.readLine()) != null) {
            response.append(inputLine);
        }

        System.out.println("result from server:"+response.toString());

        conn.disconnect();

    } catch (Exception e) {

        e.printStackTrace();
        return null;
    }
    return  response.toString();
}
你应该使用

异步任务或处理程序


表现出努力。分享你的代码。对不起,我刚刚编辑了我的帖子。现在检查。是的,就像下面说的“微笑”,你有其他选择去做GET或POST。我更喜欢截击,但首先:在Manifest.XML上添加应用程序标记之前,您是否已经说明了必要的说明和步骤?谢谢您的回复。是的,我已经在manifestNice中添加了该权限,那么,请尝试发布您的stacktrace,以便我们在崩溃发生时查看您的日志。谢谢,谢谢,我正在调查。但是我还是有点困惑。由于我只想在php页面上发布一个字符串,我会将参数更改为公共静态字符串httpPostString域、字符串根、字符串体、字符串令牌,并删除用户名吗?因为我没有在这里使用注册。是的,做任何你想做的事:。使用Http POST创建数据,GET检索数据,PUT修改,DELETE删除数据非常令人钦佩。。。恭喜你!另外,我对标记值有点困惑。如果我想将该字符串发布到php页面,那么我的值应该是什么?或者我如何找到这个值。令牌是散列字符串,您可以在stackoverflow中阅读更多关于它的内容
 nameValuePairs.add(new BasicNameValuePair("orderinfo", "Chicken sandwich: 
 tomatoes, onions, cheese.\nTotal: $5.99."));
 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
 httpclient.execute(httppost); //ERROR FROM HERE
public static String httpPost(String domain, String root, String body,
        String token, String username)
{
    String urlString = "http://"+domain+"/"+root;

    Log.d("httpPost-url",
            " url:"+urlString+
            " ,token:"+token+
            " ,httpPost-body:"+ body+
            " ,username:"+username);

    StringBuffer response = new StringBuffer();
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        if(token!=null)
        {
            conn.setRequestProperty("Authorization", "Basic " + token);
        }
        if(username!=null)
        {
            conn.setRequestProperty("Username", username);
        }
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(body);
        writer.flush();
        BufferedReader br = null;
        try
        {
            Log.d("HttpUtil", "Http code:" + conn.getResponseCode());

            br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        }
        catch (IOException e)
        {
            e.printStackTrace();
            br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
        }
        String inputLine;
        while ((inputLine = br.readLine()) != null)
        {
            response.append(inputLine);
        }
        System.out.println("result from server:"+response.toString());
        conn.disconnect();

    }
    catch (Exception e)
    {
        e.printStackTrace();
        return null;
    }
    return  response.toString();
}


public static String httpGet(String domain, String urlRoot, String token,
                             String username)
{
    String urlString = "http://"+domain+"/"+urlRoot;
    Log.d("httpGet-url:",
            " url:"+urlString+
            " ,token:"+token+
            " ,username:"+username);
    StringBuffer response = new StringBuffer();
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json");
        if(token!=null)
        {
            conn.setRequestProperty("Authorization", "Basic " + token);
        }
        if(username!=null)
        {
            conn.setRequestProperty("Username", username);
        }
        Log.d("HttpUtil","Http code:"+conn.getResponseCode());

        BufferedReader br=null;

        if(conn.getResponseCode()>=200&&conn.getResponseCode()<300) {
            br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        }
        else if(conn.getResponseCode()>=400)
        {
            br = new BufferedReader(new InputStreamReader((conn.getErrorStream())));
        }

        String inputLine;
        while ((inputLine = br.readLine()) != null) {
            response.append(inputLine);
        }

        System.out.println("result from server:"+response.toString());

        conn.disconnect();

    } catch (Exception e) {

        e.printStackTrace();
        return null;
    }
    return  response.toString();
}
android.os.NetworkOnMainThreadException
private class LoginTask extends AsyncTask<String, Void, String> {

    private ProgressDialog progress;

    protected String doInBackground(String... params)
    {
        LoginActivity.this.runOnUiThread(new Runnable() {
            public void run() {
                progress = new ProgressDialog(LoginActivity.this);
                progress.setTitle(getResources().getString(R.string.app_name));
                progress.setMessage(getResources().getString(R.string.loading));
                progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                progress.setCancelable(true);
                progress.show();
            }
        } );

        String result = HttpUtil.httpPost(
                params[0],params[1],
                params[2], params[3],
                params[4]);

        return result;
    }

    protected void onPostExecute(String param) {
        progress.dismiss();

        if(param==null)
        {
            return ;
        }
        Log.d("onPostExecute:",param);
        try
        {
            LoginDTO result = new JSONDeserializer<LoginDTO>()
                    .use("data", DataLoginDTO.class)
                    .use("data.rights.values", RightObjectDTO.class)
                    .deserialize(param, LoginDTO.class);
            if(result.getData()!=null)
            {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                //intent.putExtra;
                Bundle bundle = new Bundle();
                //bundle.putParcelableArrayList("rights", result.getData().getRights());

                String rightString= new JSONSerializer().serialize(result.getData().getRights());

                intent.putExtras(bundle);
                String token = result.getData().getToken();
                SharedPreferences sharedPref = LoginActivity.this.getSharedPreferences(getResources()
                        .getString(R.string.preference_file_key),  Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString("token", token);
                editor.putString("username", usernameEditText.getText().toString());
                editor.putLong("employeeId", result.getData().getEmployeeId());
                editor.putString("rights", rightString);
                editor.commit();

                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                    startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(LoginActivity.this).toBundle());
                }
                else
                {
                    startActivity(intent);
                }

            }
            else
            {
                android.app.AlertDialog dialog = new android.app.AlertDialog.Builder(LoginActivity.this)
                        .setTitle(R.string.app_name)
                        .setMessage(R.string.incorrect_username_or_password)
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which)
                            {
                                dialog.dismiss();
                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            AlertDialog dialog = new AlertDialog.Builder(LoginActivity.this)
                    .setTitle(R.string.error)
                    .setMessage(R.string.an_error_has_occurred)
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();

        }
    }
}