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

标签 java json wcf

我有一个接受 byte[] serialData 的 wcf 服务,现在正在开发一个需要使用相同方法的 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);

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()+"\"}";

这是我的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
        }
    }

这是我的方法调用:

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

最佳答案

下面是一个简单的工作原型(prototype),用于从字符串实例生成 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);

    }
}

更新:

代码使用 Java 8 SDK。如果您使用的是 Java8 之前的版本,请考虑 Apache Commons Codec为了这个任务。

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

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

    }
}

更新 2:

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

connection.setRequestMethod("POST");

并使用 HttpURLConnection 而不是 URLConnection:

import java.net.HttpURLConnection;

关于java - 如何在json post请求中发送字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24568735/

相关文章:

linq - WCF 数据服务与 EF4 的多对多关系

wcf - "Guarding"来自某些用户的WCF服务-应用程序身份

java - Mockito 模拟测试嵌套函数调用

java - 检查字符串内容

Java:播放 WAV 声音

JavaFx:文本溢出:省略号类似物

php - jQuery JSON - 为什么我收到以下错误?

java - 如何在 android 中循环 json 数组?

javascript - 如何加载包含对象对象的 JSON 文件的每个部分?

C# .NET - 以最小延迟发送大量小消息(通过网络)