2

POST リクエストを発行しようとしています。私が送信しているデータは XML 形式 (私は JAXB 経由でこれを行っています) ですが、要求パラメーターと共に送信する必要があります。私の問題はContent-Typeに関するものです(コードにいくつかのコメントを追加しました)。どちらを使用すればよいですか?

以下の私のコードを参照してください:

       private V callAndGetResponse(K request, Class<K> requestClassType, Class<V> responseClassType) throws Exception {
    JAXBContext jaxbContext = JAXBContext.newInstance(requestClassType, responseClassType);

    Marshaller marshaller = jaxbContext.createMarshaller();
    // set properties on marshaller
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, charset);
    marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", String.format(XML_HEADER_FORMAT, dtd));
    marshaller.marshal(request, System.out);

    URL wsUrl = new URL(primaryEndpointUrl);
    HttpURLConnection connection = openAndPrepareConnection(wsUrl);
    tryToMarshallWsRequestToOutputStream(request, marshaller, connection);

    printDebug(connection);

    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    Object response = unmarshaller.unmarshal(connection.getInputStream());

    // cleanup
    connection.disconnect();
    return responseClassType.cast(response);
}

private HttpURLConnection openAndPrepareConnection(URL wsUrl) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) wsUrl.openConnection();
    connection.setDoOutput(true);
    connection.setRequestProperty("Accept", "application/xml");
    connection.setRequestProperty("Accept-Charset", charset);
    // Both types ? Doesn't work
    connection.setRequestProperty("Content-Type", "application/xml;application/x-www-form-urlencoded");
    // Only app/xml ? it seems that query param is not added to request
    connection.setRequestProperty("Content-Type", "application/xml");
    // Only app/query param ? it seems that xml is not added to request
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    return connection;
}

private void tryToMarshallWsRequestToOutputStream(K request, Marshaller jaxbForRequestMarshaller,
        HttpURLConnection connection) throws JAXBException, IOException {
    OutputStream outputStream = null;
    try {
        outputStream = connection.getOutputStream();
        jaxbForRequestMarshaller.marshal(request, outputStream);
        addQueryParameters(outputStream);
    }
    finally {
        tryToClose(outputStream);
    }
}

private void addQueryParameters(OutputStream outputStream) throws IOException {
    String value = "none";
    String query = String.format("xmlmsg=%s", URLEncoder.encode(value, charset));
    outputStream.write(query.getBytes(charset));
}

protected void tryToClose(OutputStream outputStream) throws IOException {
    if (outputStream != null) {
        outputStream.close();
    }
}

どうもありがとう!

4

1 に答える 1