Passing json array in a key value pair in Java

2019-07-28 05:31发布

问题:

I'm trying to send data using rest webservice in Java. I'm able to post data using Java in POST but now I need to send data in rawModeData and I also need to send JSONArray in surveysData key.

Please find the attached screenshot

This is the Code that I'm using to send data

try {
        URL url = new URL(webServiceData.getSyncSurveyDataUrl());

        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

        // ConnectionType
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setUseCaches(false);
        httpURLConnection.setAllowUserInteraction(false);
        httpURLConnection.setRequestProperty("charset", "utf-8");
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        // Create the output form content
        OutputStream out = httpURLConnection.getOutputStream();
        Writer writer = new OutputStreamWriter(out, "UTF-8");

        JSONObject objects = new JSONObject();

        objects.put("constituency", constituency);
        objects.put("longitude", longitude);
        objects.put("latitude", latitude);
        objects.put("createdOn", createdOn);

        for (Map.Entry<String, String> map : linkedHashMap.entrySet()) {
            objects.put(map.getKey(), map.getValue());
        }

        writer.write("createdByDeviceId");
        writer.write("=");
        writer.write(URLEncoder.encode(loginModel.getDeviceId(), "UTF-8"));
        writer.write("&");
        writer.write("createdByMobileNumber");
        writer.write("=");
        writer.write(URLEncoder.encode(loginModel.getMobileNumber(), "UTF-8"));
        writer.write("&");
        writer.write("state");
        writer.write("=");
        writer.write(URLEncoder.encode(loginModel.getLoggedInState(), "UTF-8"));
        writer.write("&");
        writer.write("eventId");
        writer.write("=");
        writer.write(URLEncoder.encode(loginModel.getEventId(), "UTF-8"));
        writer.write("&");
        writer.write("surveysData");
        writer.write("=");
        writer.write(URLEncoder.encode(objects.toString(), "UTF-8"));

        if (httpURLConnection.getResponseCode() != 200) {
            System.out.println("Exception in 200: " + httpURLConnection.getResponseCode());
            System.out.println("Exception Message: " + httpURLConnection.getResponseMessage());
            /*errorLabel.setText(httpURLConnection.getResponseMessage());
            errorLabel.setVisible(true);*/
        }
    } catch (Exception e) {
        return false;
    }

I'm getting 401 error message

回答1:

I think you missed some authentication token in headers. Something like : httpURLConnection.setRequestProperty("tokenKey", "yourAuthToken");



回答2:

  • You are not connecting to connection. Also I think that you need to setFixedLengthStreamingMode on connection and write output as byte array. Example:
//...
    String queryParameters = formatQueryParameters(requestData);
    byte[] output = queryParameters.getBytes(Charset.forName("UTF-8"));
    connection.setFixedLengthStreamingMode(output.length);
    connection.connect();
    DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
    dataOutputStream.write(output);
//...
public static String formatQueryParameters(Map<String, String> requestData) throws UnsupportedEncodingException {
    String equals = URLEncoder.encode("=", "UTF-8");
    String ampersand = URLEncoder.encode("&", "UTF-8");
    StringBuilder builder = new StringBuilder();

    for (Map.Entry<String, String> entry : requestData.entrySet()) {
        String encodedKey = URLEncoder.encode(entry.getKey(), "UTF-8");
        String encodedValue = URLEncoder.encode(entry.getValue(), "UTF-8");
        builder.append(encodedKey).append(equals).append(encodedValue).append(ampersand);
    }
    builder.deleteCharAt(builder.lastIndexOf(ampersand));
    return builder.toString();
}


标签: java json rest