我怎么能发布数据到php使用json只是接收数据取决于发布的数据


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

我正在尝试使用json将数据发布到我的php文件。在我的php文件中,我想使用mySQL-Select-Statement的发布数据,并将选择返回给我的代码,并将其显示为列表。

最简单的方法是什么?

这是我的'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);
}

您可以使用volley库。Android volley是一个网络库,它的引入使网络调用更容易、更快,而无需编写大量代码。默认情况下,所有的网络调用都是异步工作的,所以我们不必再担心使用asynctask。

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

首先,您应该将代码移动到单独的线程中以避免ANR。您可以使用AsyncTask,但要注意内存泄漏。否则,您可以使用建议的volley或OkHttp。它们是帮助您管理HTTP连接并在单独线程中处理请求的库。

例如,如果你想使用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
                    }
                });
        }
    });

希望对你有帮助!!

首先,你应该知道在主UI上运行这段代码会给你错误,你试着在AsyncTask中实现它。

第二,"JSONObject jsonResponse = new JSONObject(jsonResult);"你在哪里声明"jsonResult"变量,根据你的代码,我看不到你在哪里声明。另外,你应该知道DefaultHttpClient现在已被弃用,最好使用UrlConnect进行http调用。

最后我同意Patil的观点,你应该掌握一些android网络库,如Retrofit或Volley,因为你是一个初学者。