how to send byte array in json post request?

java, json, wcf

Solution

Below, there's a simple working prototype to generate json from a string instance. Use this code snippet to update your client part. And it should work.

import java.util.Base64;

public class Test {

    public static void main(String[] args) {

        StringBuilder sb = new StringBuilder();

        // composing string to be encoded
        sb.append("Part 1 of some text to be encoded to base64 format\n");
        sb.append("Part 2 of some text to be encoded to base64 format\n");
        sb.append("Part 3 of some text to be encoded to base64 format");


        // getting base64 encoded string bytes
        byte[]   bytesEncoded = Base64.getEncoder().encode(sb.toString().getBytes());

        // composing json
        String json = "{\"serialDataByte\":\""+ new String(bytesEncoded) +"\"}";        

        System.out.println(json);

    }
}

UPDATE:

The code uses Java 8 SDK. If you are using pre-Java8 version, then consider Apache Commons Codec for this task.

Below there's a sample code, that uses Apache Commons Codec for Base64 encoding (please note that import directive has been changed):

import org.apache.commons.codec.binary.Base64;

public class Test {

    public static void main(String[] args) {

        StringBuilder sb = new StringBuilder();

        // composing string to be encoded
        sb.append("Part 1 of some text to be encoded to base64 format\n");
        sb.append("Part 2 of some text to be encoded to base64 format\n");
        sb.append("Part 3 of some text to be encoded to base64 format");


        // getting base64 encoded string bytes
        byte[] bytesEncoded =  Base64.encodeBase64(sb.toString().getBytes());

        // composing json
        String json = "{\"serialDataByte\":\""+ new String(bytesEncoded) +"\"}";        

        System.out.println(json);

    }
}

UPDATE 2:

Upon sending POST requests make sure that you have marked your request as a POST request. Do not forget this line of code, before making the request:

connection.setRequestMethod("POST");

and use HttpURLConnection instead of URLConnection:

import java.net.HttpURLConnection;

Problem

I have a wcf service which accepts `byte[] serialData`, now am developing a java client which needs to consume the same method. When i sent bytearray to the service as a json post request , it is getting an exception as `java.io.IOException: Server returned HTTP response code: 400` Here is my code: wcf method: ``` [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "saveSerialNumbers", BodyStyle = WebMessageBodyStyle.WrappedRequest)] Dictionary<string, object> saveSerialNumbers(byte[] serialData); ``` Java Client: ``` for (int i = 1; i < 100; i++) { sb.append(String.valueOf(gen())); } byte[] bytesEncoded = Base64.encodeBase64(sb.toString().getBytes()); String json = "{\"serialDataByte\":\""+sb.toString()+"\"}"; ``` This is my postrequest method: ``` public String getResultPOST(String jsonObject,String uri,String method) throws Exception{ try { URL url = new URL(uri+method); System.out.println(url.toString()); URLConnection connection = url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); OutputStreamWriter out; try { out = new OutputStreamWriter(connection.getOutputStream()); out.write(jsonObject); out.close(); } catch (Exception e) { / // TODO Auto-generated catch block e.printStackTrace(); } String line = ""; StringBuilder builder = new StringBuilder(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = in.readLine()) != null) { builder.append(line); } in.close(); return builder.toString(); } catch (Exception e) { throw e; //here is the exception } } ``` Here is my method call: ``` String json = "{\"serialData\":\""+ new String(bytesEncoded) +"\",\"guProductID\":\""+guProductID+"\",\"guStoreID\":\""+guStoreID+"\",\"securityToken\":\""+SecurityToken+"\"}"; String serialContract = serialClient.getResultPOST(json, "http://localhost:3361/EcoService.svc/Json/", "saveSerialNumbers"); ```

Original source