如何通过URL将JSON数组发布到服务器?

时间:2016-03-10 05:11:04

标签: android json http-post

我是Android新手。

我在我的onActivityResult'中有一个数据接收列表。我将它们转换为[{"name":"net","price":"20"},{"name":"samsung","price":"11220"}]格式的json数组  现在我想将它附加到一个网址,并希望像这种格式发送

http://xyz/abc/purchasedetails=[{“name”:”Samsung”,”price”=“45”},{“name”:”Nokia”,”price”=“25”},{“name”:”Lenovo”,”price”=“115”}]

到目前为止我做了什么:

public class SendDataToServer extends Fragment {

    int publishStatusCode = 0;

    public interface SendProductDetailsToServerCallbacks {
        public void OnPostExcecuteSendMilestoneDetailsToServerAsync(int _publishStatus,
                                                                    String _responseString);
    }

    SendProductDetailsToServerAsync mSendProductDetailsToServerAsync;
    SendProductDetailsToServerCallbacks mSendProductDetailsToServerCallbacks;

    @Override
    public void onAttach(Activity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        try {
            mSendProductDetailsToServerCallbacks =
                    (SendProductDetailsToServerCallbacks) activity;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }

    private class SendProductDetailsToServerAsync extends AsyncTask<Void, Void, String> {

        String DataToSend = "";

        public SendProductDetailsToServerAsync(String _DataToSend) {
            DataToSend = _DataToSend;

        }

        @Override
        protected String doInBackground(Void... params) {
            boolean isDoRequestAgain = false;
            String result = "";
            do {
                isDoRequestAgain = false;
               /* List<NameValuePair> nameValuePairs = new
                        ArrayList<NameValuePair>();*/


                JSONObject json = new JSONObject();
                try {



                    String totalUrl = "http://androidxyz.com/android/vendor/purchasedetails.jsp?purchasedetails=" + DataToSend;

                    HttpPost post = new HttpPost(totalUrl);
                    HttpClient client = new DefaultHttpClient();
                    HttpResponse response;

                    /*nameValuePairs.add(new BasicNameValuePair(
                            "milestonedata", json.toString()));*/

                    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    response = client.execute(post);
                    publishStatusCode = response.getStatusLine().getStatusCode();
                    HttpEntity entity = response.getEntity();

                    if (entity != null) {

                        InputStream instream = entity.getContent();
                        StringBuffer buffer = new StringBuffer();
                        byte[] b = new byte[4096];
                        for (int n; (n = instream.read(b)) != -1; ) {
                            buffer.append(new String(b, 0, n));
                        }

                        result = buffer.toString();

                    }
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } while (isDoRequestAgain);
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            Log.v("publishStatusCode", publishStatusCode + "");
            Log.v("result", result + "");
            mSendProductDetailsToServerCallbacks.OnPostExcecuteSendMilestoneDetailsToServerAsync(publishStatusCode, result);
        }

    }

    public void startSendMilestoneDetailsToServerAsync(String _dataToSend) {
        mSendProductDetailsToServerAsync = new SendProductDetailsToServerAsync(_dataToSend);
        mSendProductDetailsToServerAsync.execute();
    }
}

我需要做些什么改变才能使我的代码正常工作?

DataToSend是[{"name":"net","price":"20"},{"name":"samsung","price":"11220"}]

4 个答案:

答案 0 :(得分:0)

此方法将发布您的数据

public static String httpPost(HashMap<String, String> map, String url, String token) {
    Log.e("call ", "running");
    HttpRequest request;

    if(token!=null){
        request = HttpRequest.post(url).accept("application/json")
                .header("Authorization", "Token " + AppInfo.token).form(map);
    }
    else request = HttpRequest.post(url).accept("application/json").form(map);

    int responseCode = request.code();
    String text = request.body();

    Log.e("response", " "+responseCode+ " "+ text);

    if(responseCode==400){
        return "invalid_tocken";

    }
    else if(responseCode<200 || responseCode>=300) {

        return "error";
    }

    return text;
}

希望您可以将JSONArray转换为HashMap。如果您需要将其作为JSONArray本身发布,那么OkHttp库将为您提供帮助。

答案 1 :(得分:0)

你必须创建json数组,然后将其作为jasonArray.toString发布到param中。

以下是可以帮助您理解的示例。

private void generateCartJsonArray() {
    JSONArray jArrayMain = null;
    // send to php
    Set<String> keys = Utility.CartDetailsList.keySet();
    for (String key : keys) {
        if (Utility.CartDetailsList.containsKey(key)) {
            //creatign json obj for send to php
            cartObj = new JSONObject();
            try {
                cartObj.put("psid", key.toString());//psid
                cartObj.put("SelectedQuantity", String.valueOf(Utility.CartDetailsList.get(key).addQuantity));//SelectedQuantity
                cartObj.put("DiscountQuantity", String.valueOf(Utility.CartDetailsList.get(key).freeQuantity));//DiscountQuantity
                cartObj.put("FinalAmount", String.valueOf(Utility.CartDetailsList.get(key).totalprice));//final amount
                jArrayMain = jsonArray.put(cartObj);
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
        }
    }
    if (jArrayMain != null) {
        verifyOrder(jArrayMain); // verify before place order
    }
}

private void verifyOrder(final JSONArray cartarrayData) {

    final Dialog dialog = new Dialog(CartActivity.this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.progress_dialog);
    dialog.setCancelable(false);


    TextView text = (TextView) dialog.findViewById(R.id.tvProcessDialogTitle);
    if (Utility.language.equals(CartActivity.this.getResources().getString(R.string.Gujarati))) {
        text.setTypeface(Utility.AppsGujratiFont);
        text.setText(CartActivity.this.getResources().getString(R.string.verify_order_please_wait_guj));
    } else {
        text.setText(CartActivity.this.getResources().getString(R.string.verify_order_please_wait_eng));
    }

    dialog.show();


    StringRequest sr = new StringRequest(Request.Method.POST, Constant.VERIFY_MY_ORDER, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {


            mverifyOrderResponse = JSONUtils.verifyOrderResponse(response);
            dialog.dismiss();
            showVerifyMessage();

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

            dialog.dismiss();

        }
    }) {
        @Override
        protected Map<String, String> getParams() {

            String dd = selected_Date;

            Map<String, String> params = new HashMap<String, String>();
            params.put("Customer", Utility.userId);// customer id
            params.put("DeliverySlot", selected_SlotId);
            params.put("CustomerAddress", Utility.profileResponse.data.Areaid);
            params.put("DeliveryDate", selected_Date);
            params.put("productdetails", cartarrayData.toString());

            return params;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("Content-Type", "application/x-www-form-urlencoded");
            return params;
        }
    };
    AppController.getInstance().getRequestQueue().getCache().remove(Constant.VERIFY_MY_ORDER);
    AppController.getInstance().addToRequestQueue(sr);
}

答案 2 :(得分:0)

首先创建或者如果您已经有了课程

class Data{
    String name;
    String price;

    getters & setters

    create constuctore with name & price 
}

宣布一个清单&amp;设置数据

List<Data> list = new ArrayList<>();
list.add(new Data("Samsung", "10"));
list.add(new Data("Samsung", "20"));

创建数据地图&amp;将数据设置为它将此映射传递给Asynch的构造函数

HashMap<String, String> parameters = new HashMap<>();
foreach(Data d : list){
   parameters.put("name", d.getName());
   parameters.put("price",d.getPrice() );
}

在Asynch Task类中

 HashMap<String, String> parameters


 public SendProductDetailsToServerAsync(HashMap<String, String>  _parameters) {
            parameters = _parameters;
        }


@Override
    protected String doInBackground(Void... params) {
        Log.e("Response from url", webUrl);
        String json = null;
        URL url = null;
        try {
            try {
                url = new URL(webUrl+"?"+getQuery(parameters, sendingParametersType));
                Log.e("Response from url", webUrl+"?"+getQuery(parameters, sendingParametersType));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e2) {
            e2.printStackTrace();
        }
        HttpURLConnection urlConnection;

        try {
            assert url != null;
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");

            if (parameters != null) {
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);
                urlConnection.setConnectTimeout(2000);
               // OutputStream os = urlConnection.getOutputStream();
                //BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                      //  os, "UTF-8"));
                //writer.write(getQuery(parameters, sendingParametersType));
               /* writer.flush();
                writer.close();*/
               // os.close();
            }

            urlConnection.connect();

            try {

                if (urlConnection.getResponseCode() == 200) {
                    InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                    json = readStream(in);
                }else {
                    json = "{\"result\":\"fail\"}";
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                urlConnection.disconnect();
            }

        } catch (IOException e1) {
            e1.printStackTrace();
        }

        return json;
    }

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

            Log.e("Response from url", result);


        }
    }

    private String readStream(InputStream is) {
        try {
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            int i = is.read();
            while (i != -1) {
                bo.write(i);
                i = is.read();
            }
            return bo.toString();
        } catch (IOException e) {
            return "";
        }
    }

    private String getQuery(HashMap<String, String> params, String typeJsonOrParams)
            throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();

        if (AppContants.JSON.equalsIgnoreCase(typeJsonOrParams)) {
            result = new StringBuilder(new JSONObject(params).toString());
        } else if (AppContants.PARAMETERS.equalsIgnoreCase(typeJsonOrParams)) {

            boolean first = true;

            for (Entry<String, String> e : params.entrySet()) {
                if (first)
                    first = false;
                else
                    result.append("&");

                result.append(URLEncoder.encode(e.getKey(), "UTF-8"));
                result.append("=");
                if (e.getValue().equalsIgnoreCase("")) {
                    result.append("");
                } else {
                    result.append(URLEncoder.encode(e.getValue(), "UTF-8"));
                }
            }
        } else {

        }

        return result.toString();
    }

答案 3 :(得分:0)

我使用了OkHttp Library

感谢Hari Krishnan帮助我完成代码工作;这就是我所做的;在MainActivity中我写道:

 private class SendProductDetailsToServerAsync extends AsyncTask<Void, Void, String> {

        String DataToSend;

        public SendProductDetailsToServerAsync(String _DataToSend) {
            DataToSend = _DataToSend;

        }

        @Override
        protected String doInBackground(Void... voids) {
          //  JSONObject jsonObject= null;
            JSONArray jsonArr = null;
            JSONObject jsonObject = new JSONObject();
            try {
             //   jsonObject = new JSONObject(DataToSend);

                jsonArr = new JSONArray(DataToSend);
                jsonObject.put("", jsonArr);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return Http.httpPost(jsonArr, "http://../android/vendor/purchasedetails.jsp", null);


        }

然后创建了一个Http类

public class Http {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static String httpPost(JSONArray map,String url, String token) {
        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(10, TimeUnit.SECONDS);
        client.setReadTimeout(10, TimeUnit.SECONDS);
        String text="";
        Request request;
        int responseCode=1234;
        try {
            JSONArray jsonArray = map;

            String json = jsonArray.toString();
            Log.e("json", json);
            RequestBody body = RequestBody.create(JSON, json);
            Log.v("body",""+body);
            if (token!=null){
                request = new Request.Builder().url(url).header("Authorization", "Token " + token).
                        header("Connection", "close").
                        post(body).
                        build();

            Log.v("request",""+request);}
            else {
                request = new Request.Builder().url(url).
                        header("Connection", "close").
                        post(body).build();
                Log.v("requestnotoken",""+request);
            }
            Response response = client.newCall(request).execute();
            text=response.body().string();
            responseCode=response.code();
            Log.e("responseode",String.valueOf(responseCode));
            Log.e("text",text);

            if(!response.isSuccessful()) {
                Log.e("HttpPostResponse", String.valueOf(responseCode));
                return "error";
            }
        }


        catch (Exception e) {
            e.printStackTrace();
            return "error_network";
        }
        return text;
    }

}