简体   繁体   English

如何将csv文件作为表单参数发送到Java中的Web服务

[英]How to send a csv file as a form parameter to a webservice in Java

I have written a webservice which consumes form param as given below 我写了一个Web服务,它使用如下形式的参数

@POST
@Path("/upload/")
@Consumes("multipart/form-data")
@Produces("text/plain")

public String upload(@FormDataParam("model") InputStream modelInputStream,
        @FormDataParam("file") InputStream fileInputStream) {

    JsonObject userDefinedObj = new JsonObject();
    try {
        Scanner s = new Scanner(fileInputStream).useDelimiter("\\A");
        Scanner modelText = new Scanner(modelInputStream).useDelimiter("\\A");
        String modelName = modelText.hasNext() ? modelText.next() : "";
        String result = s.hasNext() ? s.next() : "";
        String delimiter = "";
        if (result.contains("\r\n"))
            delimiter = "\r\n";
        else if (result.contains("\n\r"))
            delimiter = "\r\n";
        else if (result.contains("\n"))
            delimiter = "\n";
        else if (result.contains("\r"))
            delimiter = "\r";

        String[] deviceList = result.split(delimiter);
        userDefinedObj = new JsonParser().parse(modelName).getAsJsonObject();
        String serverName = userDefinedObj.get("serverName").getAsString();
        String serverUrl = getServerUrlFromServerName(serverName);
        userDefinedObj.remove("serverName");
        JsonArray eventsArray = new JsonArray();
        for (int i = 0; i < deviceList.length; i++) {
            JsonObject eventObject = new JsonObject();
            JsonObject deviceObj = new JsonObject();
            JsonObject idTypeDefinitionsObj = new JsonObject();
            JsonArray appEventListArray = new JsonArray();
            String platform = userDefinedObj.get("appPlatform").getAsString();
            String operatingSystem = platform.equalsIgnoreCase("UNKNOWN") ? "UNKNOWN" : "";
            JsonElement operatingSystemObj = new JsonParser().parse(operatingSystem);
            JsonElement deviceIdObj = new JsonParser().parse(deviceList[i]);
            deviceObj.add("operatingSystem", operatingSystemObj);
            deviceObj.add("deviceId", deviceIdObj);
            JsonElement idTypeObj = new JsonParser().parse("DEVICE_ID");
            JsonElement alternateIdListObj = new JsonNull();
            idTypeDefinitionsObj.add("idType", idTypeObj);
            idTypeDefinitionsObj.add("idValue", deviceIdObj);
            idTypeDefinitionsObj.add("alternateIdList", alternateIdListObj);
            eventObject.add("device", deviceObj);
            eventObject.add("idTypeDefinitions", idTypeDefinitionsObj);
            eventObject.add("appEventList", appEventListArray);
            eventsArray.add(eventObject);
        }
        userDefinedObj.add("events", eventsArray);
        String url = "http://" + serverUrl + "/url/url11/events";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        con.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
        writer.write(userDefinedObj.toString());
        writer.close();
        int responseCode = con.getResponseCode();
        return String.valueOf(responseCode);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return "400";
}

Now I am writing a Junit test case which should pass data to this webservice. 现在,我正在编写一个Junit测试用例,该用例应将数据传递到此Web服务。 I tried using the below code. 我尝试使用下面的代码。 But I am getting error 415 但我收到错误415

@Test
public void postEvents() {
    try {
        String url = "http://url/url2/upload";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // optional default is GET
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        con.setRequestProperty("charset", "utf-8");
        con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        String requestPayload = "{\"accessToken\":\"abcdefg\"}";
        OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
        writer.write(requestPayload);
        writer.close();

        int responseCode = con.getResponseCode();
        assertTrue(responseCode == 200);
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        System.out.println(response.toString());
        AccessToken token = gson.fromJson(response.toString(), AccessToken.class);
        String tokenValue = token.getTokenValue();
        System.out.println();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Actually I wanted to pass a csv file and add the below data along with it. 实际上,我想传递一个csv文件并添加以下数据。

Model 模型

{ "accessToken":"abcdefg", "serverName":"SIT", "appPlatform":"UNKNOWN", "appBundleId":"com." {“ accessToken”:“ abcdefg”,“ serverName”:“ SIT”,“ appPlatform”:“ UNKNOWN”,“ appBundleId”:“ com”。 } }

form-data; 形式数据; name="file"; NAME = “文件”; filename="aa10.csv" 文件名= “aa10.csv”

I have no idea how to do it and I browsed yesterday whole day and couldn't get a related link. 我不知道该怎么做,我昨天整天都浏览了,但是没有相关的链接。 Any help would be much appreciated. 任何帮助将非常感激。 Thanks in advance. 提前致谢。

Just in case someone sees this answer in the future I resolved this issue by adding jersey client jar file as maven dependency. 万一将来有人看到这个答案,我通过添加jersey客户端jar文件作为maven依赖关系来解决此问题。 Then in the Junit test case I did the following 然后在Junit测试用例中,我做了以下工作

ClientConfig config = new DefaultClientConfig();
config.getClasses().add(MultiPartWriter.class);     
Client client = Client.create(config);

WebResource resource = client.resource(
            "http://localhost:8080/url/url11/upload");

InputStream is = App.class.getClassLoader().getResourceAsStream("aa10.csv");
String exampleString = "{\"accessToken\":\"324d393c-f564-4699- ae53-8fdcfc7b8fe6\",\"serverName\":\"SIT\",\"appPlatform\":\"UNKNOWN\",\"appBundleId\":\"com.\"}";
InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8));

FileDataBodyPart filePart = new FileDataBodyPart("file",
            new File("/Users/user/Documents/aa10.csv"));

FormDataMultiPart multipartEntity = (FormDataMultiPart) new FormDataMultiPart()
            .field("model", exampleString, MediaType.MULTIPART_FORM_DATA_TYPE).bodyPart(filePart);

ClientResponse response = resource.type(MediaType.MULTIPART_FORM_DATA_TYPE).post(ClientResponse.class,
            multipartEntity);

Now the issue got resolved and I am getting the expected response 现在问题已解决,我得到了预期的答复

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM