ReST: POST: java.io.IOException: Unsupported Media

2019-07-21 09:17发布

问题:

I'm trying to make a POST call to a local ReST service that sends back a simple XML response.

I'm getting back this error:

java.io.IOException: Unsupported Media Type
    at com.eric.RawTestPOST.httpPost(RawTestPOST.java:42)
    at com.eric.RawTestPOST.main(RawTestPOST.java:66)

I'm following this example:Link

Here is my code:

public class RawTestPOST {

public static String httpPost(String urlStr, String method,
        String parameter, String parameterValue) throws Exception {
    URL url = new URL(urlStr);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setAllowUserInteraction(false);
    conn.setRequestProperty("Content-Type",
            "application/x-www-form-urlencoded");

    // Create the form content
    OutputStream out = conn.getOutputStream();
    Writer writer = new OutputStreamWriter(out, "UTF-8");
    /* for (int i = 0; i < string.length; i++) { */
    writer.write(method);
    writer.write("?");
    writer.write(parameter);
    writer.write("=");
    writer.write(URLEncoder.encode(parameterValue, "UTF-8"));
    writer.write("&");
    /* } */
    writer.close();
    out.close();

    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }

    // Buffer the result into a string
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn
            .getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    conn.disconnect();
    return sb.toString();
}

public static void main(String[] args) {
    String url = "http://localhost:9082/ServicesWSRest/";
    String method = "getResponse";
    String parameter = "empID";
    String parameterValue = "954";
    try {
        System.out.println(RawTestPOST.httpPost(url, method, parameter,
                parameterValue));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}

The parameters are not imprtant. The XML response just returns the parameters sent in.

I can get it to work with a GET request.

Let me know if y'all need anymore information.

Thanks, E

回答1:

Unsupported Media Type indicates that the media type of the representation you POSTed to the web service ('application/x-www-form-urlencoded') isn't one the web service supports. I'd hazard a guess that the web service is expecting 'application/xml' representations. It all depends on the web app you're talking to of course.



标签: java rest post