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

时间:2015-04-17 09:34:24

标签: android

我想将SQLite database中的许多数据库发送到webserver内的PostgreSQL数据库。我知道如何将send传统的键值对数据发送到webserver,但在我的情况下,我想从{{1}发送很多 records数据库。以下是我的传统SQLite代码:

post

获取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); } } 条记录的方法:

SQLite

网络服务器端的PHP脚本:

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

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

2 个答案:

答案 0 :(得分:0)

使用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);
        }
    }

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

    }

答案 1 :(得分:0)

我用过:

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

作为url参数