Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/209.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何通过URL将JSON数组发布到服务器?_Android_Json_Http Post - Fatal编程技术网

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

Android 如何通过URL将JSON数组发布到服务器?,android,json,http-post,Android,Json,Http Post,我对安卓完全陌生 我在“onActivityResult”中有一个数据接收列表。我将它们转换为json数组,格式为[{“name”:“net”,“price”:“20”},{“name”:“samsung”,“price”:“11220”}] 现在,我想把它附加到一个url,并希望以这种格式发送 http://xyz/abc/purchasedetails=[{“name”:”Samsung”,”price”=“45”},{“name”:”Nokia”,”price”=“25”},{“name”

我对安卓完全陌生

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

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();
    }
}
公共类SendDataToServer扩展片段{
int publishStatusCode=0;
公共接口SendProductDetailsToServerCallbacks{
PostExcecuteSendMileStoneDeTailsToServerAsync(int\u publishStatus,
字符串_responseString);
}
SendProductDetailsToServerAsync mSendProductDetailsToServerAsync;
SendProductDetailsToServerCallbacks mSendProductDetailsToServerCallbacks;
@凌驾
公共事务主任(活动){
//TODO自动生成的方法存根
超级转速计(活动);
试一试{
mSendProductDetailsToServerCallbacks=
(SendProductDetailsToServerCallbacks)活动;
}捕获(例外e){
//TODO:处理异常
e、 printStackTrace();
}
}
@凌驾
创建时的公共void(Bundle savedInstanceState){
//TODO自动生成的方法存根
super.onCreate(savedInstanceState);
}
私有类SendProductDetailsToServerAsync扩展了AsyncTask{
字符串DataToSend=“”;
public SendProductDetailsToServerAsync(字符串\u DataToSend){
DataToSend=_DataToSend;
}
@凌驾
受保护字符串doInBackground(无效…参数){
布尔值isDoRequestAgain=false;
字符串结果=”;
做{
isDoRequestAgain=假;
/*List nameValuePairs=新建
ArrayList()*/
JSONObject json=新的JSONObject();
试一试{
字符串totalUrl=”http://androidxyz.com/android/vendor/purchasedetails.jsp?purchasedetails=“+数据发送;
HttpPost=新的HttpPost(总URL);
HttpClient=new DefaultHttpClient();
HttpResponse响应;
/*添加(新的BasicNameValuePair)(
“milestonedata”,json.toString())*/
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
响应=client.execute(post);
publishStatusCode=response.getStatusLine().getStatusCode();
HttpEntity=response.getEntity();
如果(实体!=null){
InputStream instream=entity.getContent();
StringBuffer=新的StringBuffer();
字节[]b=新字节[4096];
对于(int n;(n=流内读取(b))!=-1;){
append(新字符串(b,0,n));
}
结果=buffer.toString();
}
}捕获(JSONException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(不支持的编码异常e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(非法状态){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}while(isDoRequestAgain);
返回结果;
}
@凌驾
受保护的void onPostExecute(字符串结果){
//TODO自动生成的方法存根
super.onPostExecute(结果);
Log.v(“publishStatusCode”,publishStatusCode+”);
Log.v(“结果”,结果+”);
mSendProductDetailsToServerCallbacks.OnPostExcecuteSendMilestoneDetailsToServerAsync(publishStatusCode,结果);
}
}
public void startSendMilestoneDetailsToServerAsync(字符串_dataToSend){
mSendProductDetailsToServerAsync=新的SendProductDetailsToServerAsync(\u dataToSend);
mSendProductDetailsToServerAsync.execute();
}
}
我必须在这里做什么更改才能使代码正常工作


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

此方法将发布您的数据

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;
}
公共静态字符串httpPost(HashMap映射、字符串url、字符串令牌){
Log.e(“呼叫”、“运行”);
HttpRequest请求;
if(令牌!=null){
request=HttpRequest.post(url.accept)(“应用程序/json”)
.header(“授权”、“令牌”+AppInfo.Token).form(map);
}
else-request=HttpRequest.post(url.accept(“application/json”).form(map);
int responseCode=request.code();
String text=request.body();
Log.e(“响应”,“响应代码+”+文本);
如果(响应代码==400){
返回“无效_tocken”;
}
否则如果(响应代码=300){
返回“错误”;
}
返回文本;
}

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

您必须创建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);
}
private void generateCartJsonArray(){
JSONArray-jArrayMain=null;
//发送到php
Set keys=Utility.cartdailslist.keySet();
用于(字符串键:键){
if(实用程序CartDetailsList.containsKey(键)){
//创建用于发送到php的json obj
cartObj=新的JSONObject();
试一试{
卡托
class Data{
    String name;
    String price;

    getters & setters

    create constuctore with name & price 
}
List<Data> list = new ArrayList<>();
list.add(new Data("Samsung", "10"));
list.add(new Data("Samsung", "20"));
HashMap<String, String> parameters = new HashMap<>();
foreach(Data d : list){
   parameters.put("name", d.getName());
   parameters.put("price",d.getPrice() );
}
 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();
    }
 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);


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

}