简体   繁体   English

我如何才能使用json将数据发布到php,以便仅根据发布的数据来接收数据?

[英]How can i post data to php using json just to receive data depending on posted data?

i'm trying to post data to my php-file using json. 我正在尝试使用json将数据发布到我的php文件中。 In my php-file, I want to use the posted data for a mySQL-Select-Statement and return the selection to my code and displaying it as a list. 在我的php文件中,我想将发布的数据用于mySQL-Select-Statement并将选择的内容返回到我的代码中,并将其显示为列表。

What is the simpliest way to do it? 最简单的方法是什么?

This is my 'postData()': 这是我的“ postData()”:

   public void postData() {
    //trying 
    List<Map<String, String>> buyCategories = new ArrayList<Map<String, String>>();
    //trying

    try{
        // url where the data will be posted
        String postReceiverUrl = "http://www.url.de/getArticles.php";

        // HttpClient
        HttpClient httpClient = new DefaultHttpClient();

        // post header
        HttpPost httpPost = new HttpPost(postReceiverUrl);

        int cat = UsingSharedPrefs.getChosenCategorie();
        if(cat == 0) {
            cat = 100;
        }
        String cats = Integer.toString(cat);

        // add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("categorieId", cats));

        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // execute HTTP post request
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {

            JSONObject jsonResponse = new JSONObject(jsonResult);
            JSONArray jsonMainNode = jsonResponse.getJSONArray("testproducts");
            for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                String name = jsonChildNode.getString("testproduct_name");
                String price = jsonChildNode.getString("testproduct_price");
                String path = jsonChildNode.getString("testproduct_buffer");

                HashMap<String, String> hmBuyCategories = new HashMap<String,String>();
                hmBuyCategories.put("txt", "Categorie : " + name);
                hmBuyCategories.put("pri", "Price : " + price);
                hmBuyCategories.put("bes","Currency : " + path);

                int imageId = getResources().getIdentifier("jollocks.logle:drawable/" + path, null, null);

                hmBuyCategories.put("pic", Integer.toString(imageId) );

                buyCategories.add(hmBuyCategories);
                }
            String responseStr = EntityUtils.toString(resEntity).trim();
            Log.v(TAG, "Response: " +  responseStr);
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        Toast.makeText(getApplicationContext(), "Errortest" + e.toString(),
        Toast.LENGTH_SHORT).show();
    }

    String[] from = { "pic","txt","pri", "bes" };

    int[] to = { R.id.buffer,R.id.name, R.id.price, R.id.beschreibung};

    ListView listView = ( ListView ) findViewById(R.id.sampleListView);

    SimpleAdapter simpleAdapter = new SimpleAdapter(this, buyCategories,
    R.layout.list_item_product,
    from, to);
    listView.setAdapter(simpleAdapter);
}

You can use volley library. 您可以使用排球库。 Android volley is a networking library was introduced to make networking calls much easier, faster without writing tons of code. Android Volley是一个联网库,旨在使联网呼叫变得更加轻松,快捷,而无需编写大量代码。 By default all the volley network calls works asynchronously, so we don't have to worry about using asynctask anymore. 默认情况下,所有齐射网络调用均异步工作,因此我们不必担心再使用asynctask。

http://developer.android.com/training/volley/simple.html http://developer.android.com/training/volley/simple.html

First of all you should move the code in a separate thread to avoid ANR. 首先,您应该将代码移到单独的线程中以避免ANR。 You could use an AsyncTask but be aware of memory lekeage. 您可以使用AsyncTask,但要注意内存泄漏。 Otherwise you can use volley as suggested or OkHttp. 否则,您可以按照建议使用Volley或OkHttp。 They are libraries that help you to manage HTTP connection and handle requests in a separate thread. 它们是可帮助您管理HTTP连接并在单独的线程中处理请求的库。

For example if you want to use OkHttp: 例如,如果您想使用OkHttp:

  OkHttpClient client = new OkHttpClient();
  Request request = new Request.Builder().url(url).build();
  client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Request request, IOException e) {
           // Notify error
        }

        @Override
        public void onResponse(Response response) throws IOException {

               // Here you parse the response
               // when ready update the View
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        // Here you update the listview
                    }
                });

        }
    });

Hope it will help you!! 希望对你有帮助!!

First of all, you should know that running this code on the main UI would give you errors, you try implementing this in a AsyncTask. 首先,您应该知道在主UI上运行此代码会给您带来错误,您尝试在AsyncTask中实现它。

Secondly, "JSONObject jsonResponse = new JSONObject(jsonResult);" 其次,“ JSONObject jsonResponse =新的JSONObject(jsonResult);” where did you declare the "jsonResult" variable, according to your codes i don't see where you declared. 您在哪里声明了“ jsonResult”变量,根据您的代码,我看不到您声明的位置。 Also you should know that DefaultHttpClient is now deprecated, its better to use UrlConnect for your http calls. 您还应该知道DefaultHttpClient已被弃用,最好将UrlConnect用于您的http调用。

Lastly i agree with Patil, you should get your hands on some android networking libraries eg Retrofit or Volley and play around with since you are a beginner. 最后,我同意Patil的观点,由于您是初学者,因此您应该接触一些android联网库(例如Retrofit或Volley)并尝试一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM