如何在json post请求中发送字节数组?

Saj*_*ran 6 java wcf json

我有一个接受的wcf服务 byte[] serialData,现在正在开发一个需要使用相同方法的java客户端.

当我将bytearray作为json post请求发送到服务时,它将获得异常 java.io.IOException: Server returned HTTP response code: 400

这是我的代码:

wcf方法:

[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "saveSerialNumbers", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
Dictionary<string, object> saveSerialNumbers(byte[] serialData);
Run Code Online (Sandbox Code Playgroud)

Java客户端:

for (int i = 1; i < 100; i++) {      
                sb.append(String.valueOf(gen()));
    }
byte[]   bytesEncoded = Base64.encodeBase64(sb.toString().getBytes());
String json = "{\"serialDataByte\":\""+sb.toString()+"\"}";
Run Code Online (Sandbox Code Playgroud)

这是我的postrequest方法:

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
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是我的方法调用:

 String json = "{\"serialData\":\""+ new String(bytesEncoded)  +"\",\"guProductID\":\""+guProductID+"\",\"guStoreID\":\""+guStoreID+"\",\"securityToken\":\""+SecurityToken+"\"}";
 String serialContract  = serialClient.getResultPOST(json, "http://localhost:3361/EcoService.svc/Json/", "saveSerialNumbers");
Run Code Online (Sandbox Code Playgroud)

小智 8

下面是一个简单的工作原型,用于从字符串实例生成json.使用此代码段更新您的客户端部分.它应该工作.

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

    }
}
Run Code Online (Sandbox Code Playgroud)

更新:

该代码使用Java 8 SDK.如果您使用的是Java8之前的版本,那么请考虑使用Apache Commons Codec来完成此任务.

下面是一个示例代码,它使用Apache Commons Codec进行Base64编码(请注意,import指令已更改):

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

    }
}
Run Code Online (Sandbox Code Playgroud)

更新2:

发送POST请求后,请确保已将请求标记为POST请求.在发出请求之前,请不要忘记这行代码:

connection.setRequestMethod("POST");
Run Code Online (Sandbox Code Playgroud)

并使用HttpURLConnection而不是URLConnection:

import java.net.HttpURLConnection;
Run Code Online (Sandbox Code Playgroud)