通过Asynctask将字符串发布到外部URL

时间:2016-06-15 15:50:23

标签: php android android-asynctask

目前我正在通过外部URL检索数据,该URL使用PHP脚本并返回JSON值。它工作正常。

但是如何发送一个String用于查询,以便我可以在PHP脚本中执行以下操作:

$name = $_POST['name']; //this was sent from the Android app. How do I send this from the app.
$sql = "SELECT name FROM tablename WHERE category = '$name'";
$result = mysqli_query($con, $sql) or die("Error in Selecting");

注意:我不想使用Volley。

我的AsyncTask扩展类,目前不会将任何值发送到网址。

class BackgroundTask extends AsyncTask<Void,Void,String> {

        final String jsonUrl = "http://example.com/getdata.php";

        @Override
        protected String doInBackground(Void... params) {
            try {
                URL url = new URL(jsonUrl);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                InputStream in = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
                StringBuilder stringBuilder = new StringBuilder();

                while ((jsonString = bufferedReader.readLine()) != null){
                    stringBuilder.append(jsonString+"\n");
                }

                bufferedReader.close();
                in.close();
                httpURLConnection.disconnect();
                return stringBuilder.toString().trim();

            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            products = new ArrayList<>();

            try {
                jsonObject = new JSONObject(s);
                String category = jsonObject.getString("viewProduct");
                JSONArray jsonArray = new JSONArray(category);

                for(int x=0; x < jsonArray.length(); x++){
                    JSONObject jsonPart = jsonArray.getJSONObject(x);
                    products.add(jsonPart.getString("name"));
                }

                adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, products);
                productListView.setAdapter(adapter);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

如果你只是在谈论发送数据作为POST请求的主体,你可以这样做:

HttpURLConnection conn= (HttpURLConnection) url.openConnection();           
conn.setDoOutput( true );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
try {
   DataOutputStream wr = new DataOutputStream( conn.getOutputStream());
   wr.write( postData );
} catch (IOException ex) {}