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

时间:2017-02-02 05:07:15

标签: java web-services rest csv

我写了一个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";
}

现在我正在编写一个应该将数据传递给此Web服务的Junit测试用例。我尝试使用以下代码。但我收到错误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();
    }
}

实际上我想传递一个csv文件并添加以下数据。

  

模型

     

{   “的accessToken”: “ABCDEFG”   “服务器名”:“坐”,   “appPlatform”: “未知”,   “appBundleId”: “融为一体。”   }

     

形式数据; NAME = “文件”;文件名= “aa10.csv”

我不知道怎么做,我昨天整天浏览,无法获得相关链接。任何帮助将非常感激。提前谢谢。

1 个答案:

答案 0 :(得分:0)

以防有人在将来看到这个答案我通过添加jersey客户端jar文件作为maven依赖来解决了这个问题。然后在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);

现在问题得到了解决,我得到了预期的回复