如何将一个String数组作为发布数据发送到Web服务器?

时间:2022-12-01 16:03:07

I want to send many database rows from the SQLite database to a PostgreSQL database inside a webserver. I know how to send traditional key-value pair data to a webserver , but in my case I want to send many records from the SQLite database. Here is my code of traditional post which works :

我想将许多数据库行从SQLite数据库发送到Web服务器内的PostgreSQL数据库。我知道如何将传统的键值对数据发送到Web服务器,但在我的情况下,我想从SQLite数据库发送许多记录。这是我的传统帖子的代码:

private void postData(String p_url) {

    String donnees = ""; // here are the data to post

    try {

            donnees = URLEncoder.encode("identifiant1", "UTF-8")+ "="+URLEncoder.encode("valeur1", "UTF-8");
            donnees += "&"+URLEncoder.encode("identifiant2", "UTF-8")+ "=" + URLEncoder.encode("valeur2", "UTF-8"); // traditional key-value pair for posting data

            HttpURLConnection urlConnection = null;
            OutputStreamWriter writer = null;

            try {
                URL url = new URL(p_url);
                try {
                    urlConnection = (HttpURLConnection)url.openConnection();
                    urlConnection.setDoOutput(true);
                    urlConnection.setChunkedStreamingMode(0);
                    writer = new OutputStreamWriter(urlConnection.getOutputStream());
                    writer.write(donnees);
                    writer.flush();
                } catch (IOException e) {
                    error = true;
                    err = contextInsideDialogue.getResources().getString(R.string.errAccessError);
                } finally {
                    if (writer != null) { try { writer.close(); } catch (IOException e) {} }
                    if (urlConnection != null) { urlConnection.disconnect(); }
                }

            } catch (MalformedURLException e) {
                error = true;
                err = contextInsideDialogue.getResources().getString(R.string.errBadUrl);
            }

        } catch (UnsupportedEncodingException e1) {
            error = true;
            err = contextInsideDialogue.getResources().getString(R.string.errEncodageUTF8);
        }

}

Method to get SQLite records :

获取SQLite记录的方法:

public ArrayList<Parcelle> getAllNewOrModifiedParcelles() {
        ArrayList<Parcelle> parcelles = new ArrayList<Parcelle>();
        String selectQuery = "SELECT * FROM " + T_PARCELLE + " WHERE bien_code != '0' AND ( updated = 'true' OR new_enreg = 'true')";
        Cursor c = bd.rawQuery(selectQuery, null);
        if (c != null && c.moveToFirst()) {
            do {
                Parcelle p = new Parcelle();
                p.setBien_code(c.getString(0));
                p.setDecoup_terri_code(c.getString(1));
                p.setDec_decoup_terri_code(c.getString(2));
                p.setBien_ident(c.getString(3));
                p.setParcel_denomination(c.getString(4));
                p.setParcel_porte_ppale(c.getString(5));
                p.setParcel_porte_second(c.getString(6));
                p.setParcel_superfi_totale(c.getString(7));
                p.setParcel_superf_batie(c.getString(8));
                p.setParcel_superf_non_batie(c.getString(9));
                p.setParcel_superf_plani(c.getString(10));
                p.setParcel_adresse(c.getString(11));
                p.setParcel_date_deb_construct(c.getString(12));
                p.setParcel_date_fin_construct(c.getString(13));
                parcelles.add(p);
            } while (c.moveToNext());
        }
        return parcelles;
    }

The PHP script at the webserver side :

Web服务器端的PHP脚本:

$photo = new photo($db->getInstance(), T_PHOTO);

$tab = array();

$tab['photo_chemin'] = $_POST['identifiant1'];

$photo->ajouter($tab);

So how to construct the data to send in this case ?

那么在这种情况下如何构造要发送的数据呢?

2 个解决方案

#1


0  

Using JSON seems appropriate for your use case, here is how I have done it:

使用JSON似乎适合您的用例,这是我如何做到的:

private void postJSON(String myurl) throws IOException {
        java.util.Date date= new java.util.Date();
        Timestamp timestamp = (new Timestamp(date.getTime()));
        try {
            JSONObject parameters = new JSONObject();
            parameters.put("timestamp",timestamp);
            parameters.put("jsonArray", new JSONArray(Arrays.asList(makeJSON())));
            parameters.put("type", "Android");
            parameters.put("mail", "xyz@gmail.com");
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //  conn.setReadTimeout(10000 /* milliseconds */);
            //  conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestProperty( "Content-Type", "application/json" );
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            OutputStream out = new BufferedOutputStream(conn.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
            writer.write(parameters.toString());
            writer.close();
            out.close();

            int responseCode = conn.getResponseCode();
        //  System.out.println("\nSending 'POST' request to URL : " + url);
        //  System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        //  System.out.println(response.toString());

        }catch (Exception exception) {
            System.out.println("Exception: "+exception);
        }
    }

Here is my makeJSON method, which is similar to your use case of reading from SQLite and then converting into JSON:

这是我的makeJSON方法,类似于从SQLite读取然后转换为JSON的用例:

public JSONArray makeJSON(){

        mCur = dbHelper.makeJSONBackup(); 

        if(mCur != null && mCur.moveToFirst()){
            do{
                try{
                    //NotificationDateFor, TypeNotification, DOB, FriendsName, imageUri, RadioType FROM Notifications
                    JSONObject jObj = new JSONObject(); 
                    String notificationDateFor = mCur.getString(mCur.getColumnIndexOrThrow("NotificationDateFor")); 
                    String typeNotification =  mCur.getString(mCur.getColumnIndexOrThrow("TypeNotification"));
                    String dob = mCur.getString(mCur.getColumnIndexOrThrow("DOB"));
                    String friendsName = mCur.getString(mCur.getColumnIndexOrThrow("FriendsName"));
                    String imageUri =  mCur.getString(mCur.getColumnIndexOrThrow("imageUri"));
                    if(imageUri.contains("/data/data/com.exa")){

                    }



                    String radioType = mCur.getString(mCur.getColumnIndexOrThrow("RadioType"));


                    jObj.put("NotificationDateFor", notificationDateFor); 
                    jObj.put("DOB", dob); 
                    jObj.put("TypeNotification", typeNotification);
                    jObj.put("FriendsName", friendsName); 
                    jObj.put("imageUri", imageUri); 
                    jObj.put("RadioType", radioType); 
                    jArr.put(jObj); 

                }catch(Exception e){
                    System.out.println("Exception: "+e);
                }
            }while(mCur.moveToNext());

        }
        return jArr;

    }

#2


0  

i have used:

我用过:

values[]=stringarrayitem1&values[]=stringarrayitem2&values[]=stringarrayitem3

as the url arguments

作为url参数

#1


0  

Using JSON seems appropriate for your use case, here is how I have done it:

使用JSON似乎适合您的用例,这是我如何做到的:

private void postJSON(String myurl) throws IOException {
        java.util.Date date= new java.util.Date();
        Timestamp timestamp = (new Timestamp(date.getTime()));
        try {
            JSONObject parameters = new JSONObject();
            parameters.put("timestamp",timestamp);
            parameters.put("jsonArray", new JSONArray(Arrays.asList(makeJSON())));
            parameters.put("type", "Android");
            parameters.put("mail", "xyz@gmail.com");
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //  conn.setReadTimeout(10000 /* milliseconds */);
            //  conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestProperty( "Content-Type", "application/json" );
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            OutputStream out = new BufferedOutputStream(conn.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
            writer.write(parameters.toString());
            writer.close();
            out.close();

            int responseCode = conn.getResponseCode();
        //  System.out.println("\nSending 'POST' request to URL : " + url);
        //  System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        //  System.out.println(response.toString());

        }catch (Exception exception) {
            System.out.println("Exception: "+exception);
        }
    }

Here is my makeJSON method, which is similar to your use case of reading from SQLite and then converting into JSON:

这是我的makeJSON方法,类似于从SQLite读取然后转换为JSON的用例:

public JSONArray makeJSON(){

        mCur = dbHelper.makeJSONBackup(); 

        if(mCur != null && mCur.moveToFirst()){
            do{
                try{
                    //NotificationDateFor, TypeNotification, DOB, FriendsName, imageUri, RadioType FROM Notifications
                    JSONObject jObj = new JSONObject(); 
                    String notificationDateFor = mCur.getString(mCur.getColumnIndexOrThrow("NotificationDateFor")); 
                    String typeNotification =  mCur.getString(mCur.getColumnIndexOrThrow("TypeNotification"));
                    String dob = mCur.getString(mCur.getColumnIndexOrThrow("DOB"));
                    String friendsName = mCur.getString(mCur.getColumnIndexOrThrow("FriendsName"));
                    String imageUri =  mCur.getString(mCur.getColumnIndexOrThrow("imageUri"));
                    if(imageUri.contains("/data/data/com.exa")){

                    }



                    String radioType = mCur.getString(mCur.getColumnIndexOrThrow("RadioType"));


                    jObj.put("NotificationDateFor", notificationDateFor); 
                    jObj.put("DOB", dob); 
                    jObj.put("TypeNotification", typeNotification);
                    jObj.put("FriendsName", friendsName); 
                    jObj.put("imageUri", imageUri); 
                    jObj.put("RadioType", radioType); 
                    jArr.put(jObj); 

                }catch(Exception e){
                    System.out.println("Exception: "+e);
                }
            }while(mCur.moveToNext());

        }
        return jArr;

    }

#2


0  

i have used:

我用过:

values[]=stringarrayitem1&values[]=stringarrayitem2&values[]=stringarrayitem3

as the url arguments

作为url参数