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

时间:2017-05-08 00:44:39

标签: php android mysql string web

我是Android开发的新手,我正在尝试为一个允许用户订购食物的类项目制作一个Android应用程序。一旦他们点击结账按钮,就会有一个字符串值,其中包含用户的订单信息(即-Chicken三明治,西红柿,生菜,蛋黄酱,特殊说明,总价:5.99美元),这些信息将传递给下一个活动。但是,我还希望将此信息从应用程序发送到网站,以便查看网页的人可以查看订单信息。最好的方法是什么?

我想知道如何使用MySQL和phpmyadmin处理用户登录/注册,但我不确定是否再次为此特定字符串执行此操作是显示食物订单的最佳方式。我不打算专门为一个String创建一个数据库。相反,我只想在网页上发布该订单信息,以便"工作人员"可以查看订单信息并开始处理食品订单。

我从这篇文章中找到了一些信息:How to send a data to a web server from Android

这是我到目前为止根据我发现的内容尝试的内容: 订单列表活动:

@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;


    }
}

mypage.php

<?php
$filename="datatest.html";
file_put_contents($filename,$_POST["orderinfo"]."<br />",FILE_APPEND);
$msg=file_get_contents($filename);
echo $msg; ?>

不幸的是,这导致我的代码崩溃,并且不会向mypage.php发布任何内容。我该如何解决这个问题?

错误:     致命异议:主要     处理:com.example.kusha.finalproject,PID:5291

android.os.NetworkOnMainThreadException
                                                                              at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
                                                                              at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86)
                                                                              at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
                                                                              at java.net.InetAddress.getAllByName(InetAddress.java:752)
                                                                              at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:142)
                                                                              at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:169)
                                                                              at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:124)
                                                                              at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:366)
                                                                              at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:560)
                                                                              at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:492)
                                                                              at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:470)
                                                                              at com.example.kusha.finalproject.Orderlist.onClick(Orderlist.java:192)
                                                                              at android.view.View.performClick(View.java:5637)
                                                                              at android.view.View$PerformClick.run(View.java:22429)
                                                                              at android.os.Handler.handleCallback(Handler.java:751)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                              at android.os.Looper.loop(Looper.java:154)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

- 错误似乎来自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

谢谢!

1 个答案:

答案 0 :(得分:0)

您应该阅读有关Restful Web服务的信息。 Android将带有Json(或XML)字符串数据的Http Request(可选)发送到server.Server(.Net MVC,Spring MVC,PHP ...)接收该请求,使用业务逻辑处理它,更新数据库并返回Json字符串结果到Android。登录成功后,服务器必须发送一个令牌给移动,android存储此令牌以验证下一个请求。在您的情况下,您可以使用Http Request 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();
}

享受编码!

编辑1

android.os.NetworkOnMainThreadException

你应该使用

AsyncTaskHandler

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();

        }
    }
}