使用具有异步任务的帖子

时间:2018-01-28 05:15:40

标签: android json android-asynctask httpclient

我试图将一些数据发布为原始json。但是服务器只接收json对象而不是完整格式的json字符串。以下是我的asyc方法:

    public class SendOrderReviewPostRequest extends AsyncTask<backendPlaceOrderRequest, Void, JSONObject> {
        @Override
        protected JSONObject doInBackground(backendPlaceOrderRequest... backendPlaceOrderRequests) {
            try {
                if(backendPlaceOrderRequests.length>0){
//                    URL url = new URL( ServiceGenerator.BASE_URL+"api-v2/placeOrder/review");
                    URL url = new URL("http://myurl.com");
                    backendPlaceOrderRequest orderReq = backendPlaceOrderRequests[0];

                    JSONObject postDataParams = new JSONObject();
                    postDataParams.put("key", securityKey);
                    postDataParams.put("storeLanguageId", StoreLanguageId);

                    JSONArray arrayProduct = new JSONArray();
                    for(int i = 0; i< orderReq.product.size();i++){
                        backendPostOrderProduct product = orderReq.product.get(i);
                        JSONObject postParams = new JSONObject();
                        postParams.put("id", product.id);
                        postParams.put("qty", product.qty);
                        arrayProduct.put(postParams);
                    }
                    postDataParams.put("product",arrayProduct);

                    JSONObject postDataAddress = new JSONObject();

                    JSONObject postDataAddressBilling = new JSONObject();
                    postDataAddressBilling.put("firstname", orderReq.addresses.billing.firstname);
                    postDataAddressBilling.put("lastname", orderReq.addresses.billing.lastname);
                    postDataAddressBilling.put("street", orderReq.addresses.billing.street);
                    postDataAddressBilling.put("city", orderReq.addresses.billing.city);
                    postDataAddressBilling.put("region", orderReq.addresses.billing.region);
                    postDataAddressBilling.put("postcode", orderReq.addresses.billing.postcode);
                    postDataAddressBilling.put("telephone", orderReq.addresses.billing.telephone);
                    postDataAddressBilling.put("customer_address_lat", orderReq.addresses.billing.customer_address_lat);
                    postDataAddressBilling.put("customer_address_lng", orderReq.addresses.billing.customer_address_lng);
                    postDataAddressBilling.put("customer_address_opt_phone", orderReq.addresses.billing.customer_address_opt_phone);

                    JSONObject postDataAdd = new JSONObject();
                    postDataAdd.put("billing",postDataAddressBilling);

                    postDataParams.put("addresses",postDataAdd);

                    JSONObject postDataAddressShipping = new JSONObject();
                    postDataAddressShipping.put("firstname", orderReq.addresses.shipping.firstname);
                    postDataAddressShipping.put("lastname", orderReq.addresses.shipping.lastname);
                    postDataAddressShipping.put("street", orderReq.addresses.shipping.street);
                    postDataAddressShipping.put("city", orderReq.addresses.shipping.city);
                    postDataAddressShipping.put("region", orderReq.addresses.shipping.region);
                    postDataAddressShipping.put("postcode", orderReq.addresses.shipping.postcode);
                    postDataAddressShipping.put("telephone", orderReq.addresses.shipping.telephone);
                    postDataAddressShipping.put("customer_address_lat", orderReq.addresses.shipping.customer_address_lat);
                    postDataAddressShipping.put("customer_address_lng", orderReq.addresses.shipping.customer_address_lng);
                    postDataAddressShipping.put("customer_address_opt_phone", orderReq.addresses.shipping.customer_address_opt_phone);

                    JSONObject postDataShip = new JSONObject();
                    postDataShip.put("shipping",postDataAddressShipping);
                    postDataParams.put("addresses",postDataShip);

                    postDataParams.put("coupon", orderReq.coupon);
                    postDataParams.put("customerId", orderReq.customerId);
                    postDataParams.put("newCustomerAddress", orderReq.newCustomerAddress);
                    postDataParams.put("paymentMethod", null);
                    postDataParams.put("shippingMethod", "firstfreeship_firstfreeship");

                    JSONObject postDataPayment = new JSONObject();
                    postDataPayment.put("method", null);
                    postDataParams.put("payment", postDataPayment);

                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setReadTimeout(15000 /* milliseconds */);
                    conn.setConnectTimeout(15000 /* milliseconds */);
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                    conn.setDoInput(true);
                    conn.setDoOutput(true);

                    OutputStream os = conn.getOutputStream();
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                    writer.write(getPostDataString(postDataParams));
                    writer.flush();
                    writer.close();
                    os.close();

                    int responseCode=conn.getResponseCode();

                    if (responseCode == HttpsURLConnection.HTTP_OK) {

                        BufferedReader in=new BufferedReader(
                                new InputStreamReader(
                                        conn.getInputStream()));
                        StringBuffer sb = new StringBuffer("");
                        String line="";

                        while((line = in.readLine()) != null) {

                            sb.append(line);
                            break;
                        }

                        in.close();
                        JSONObject jsonObjRecv = new JSONObject(sb.toString());
                        return jsonObjRecv;
                    }
                    else {
                        return null;
                    }
                }else {
                    return null;
                }

            }
            catch (Exception e) {
                e.printStackTrace();
                if (mProgressDialog!=null && mProgressDialog.isShowing())
                    mProgressDialog.dismiss();
            }
            return null;
        }

        @Override
        protected void onPreExecute(){}

        @Override
        protected void onPostExecute(JSONObject result) {
//            Toast.makeText(getApplicationContext(), result,
//                    Toast.LENGTH_LONG).show();
//            backendGetHyperPayTransaction storeLanguage = result.get;
            if (mProgressDialog!=null && mProgressDialog.isShowing())
                mProgressDialog.dismiss();
            try{
                if(result.getString("message").equals("success")) {
//                backendGetHyperPayTransactionResponse bpor = storeLanguage.getHyperPayTransactionResponse();
//                    gotoOrderComplete(orderID,orderPageHeading,orderPageContent);
                }else{
                    JSONObject res = result.getJSONObject("result");
                    if(res != null && res.getString("description") != null){
//                        Toast.makeText(getApplicationContext(), res.getString("description"), Toast.LENGTH_LONG).show();
                        AlertDialog.Builder builder1 = new AlertDialog.Builder(CheckoutOrderActivity.this);
                        builder1.setMessage(res.getString("description"));
                        builder1.setCancelable(true);

                        builder1.setPositiveButton(
                                "Done",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });
                        AlertDialog alert11 = builder1.create();
                        alert11.show();
                    }
                }
            }catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

使用下面的方法将json对象转换为字符串:

public String getPostDataString(JSONObject params) throws Exception {

    StringBuilder result = new StringBuilder();
    boolean first = true;

    Iterator<String> itr = params.keys();

    while(itr.hasNext()){

        String key= itr.next();
        Object value = params.get(key);

        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(key, "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(value.toString(), "UTF-8"));

    }
    return result.toString();
}

我知道问题是因为json字符串无法发送,因为当我尝试将其硬编码为字符串时,它会起作用。

0 个答案:

没有答案