如何在android中使用get方法在url中设置json数组?

时间:2018-07-06 08:40:11

标签: android httprequest

http://192.168.0.14/something/storeAnswerGet?longitude=20.49158053365199&latitude=44.798944935485885&answers="[{\"id\":3,\"id_question\":7,\"user_id\":1,\"answer\":\"Beograd\"},{\"id\":3,\"id_question\":7,\"user_id\":1,\"answer\":\"Valjevo\"},{\"id\":3,\"id_question\":8,\"user_id\":1,\"answer\":\"Da\"}]"

问题在&answers=之后,无法识别为url的一部分, 格式为JsonObject的字符串。

2 个答案:

答案 0 :(得分:1)

在这里解释: https://stackoverflow.com/a/27578923/1088975

基本上您有2个选择

  1. 使用POST方法发送数据
  2. 编码文本并发送GET

答案 1 :(得分:0)

基本上storeAnswerpost请求,并且payload将以body格式添加到请求json

public void sendAnswerRequest(){
    try {
        URL url = new URL("http://192.168.0.14/something/storeAnswerGet");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        conn.setRequestProperty("Accept","application/json");
        conn.setDoOutput(true);
        conn.setDoInput(true);

        JSONObject jsonParam = new JSONObject();
        jsonParam.put("latitude", 44.798944935485885);
        jsonParam.put("longitude", 20.49158053365199);

        JSONArray answers = new JSONArray();

        JSONObject answer = new JSONObject();
        answer.put("id",3);
        answer.put("id_question",7);
        answer.put("user_id",1);
        answer.put("answer","Beograd");

        answers.put(answer); // Add all answers to answer array..

        jsonParam.put("answers",answers);

        Log.i("JSON", jsonParam.toString());
        DataOutputStream os = new DataOutputStream(conn.getOutputStream());
        //os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
        os.writeBytes(jsonParam.toString());

        os.flush();
        os.close();

        Log.i("STATUS", String.valueOf(conn.getResponseCode()));
        Log.i("MSG" , conn.getResponseMessage());

        conn.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
}