2012-01-05 28 views
2

我試圖對發送回簡單的XML響應的本地ReST服務進行POST調用。重試:POST:java.io.IOException:不支持的媒體類型

我又回到這個錯誤:

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

我下面這個例子:Link

這裏是我的代碼:

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

的參數不imprtant。 XML響應只是返回發送的參數。

我可以讓它與GET請求一起工作。

讓我知道你們是否需要任何信息。

感謝, ē

+0

這可能是特定於要連接的服務器,因爲它是服務器返回的答案,而不是Java網絡代碼;例如,服務器可以指定它不支持您請求的特定資源的POST請求。你能提供更多關於你連接的服務器的信息嗎? – Seramme 2012-01-05 23:09:10

回答

1

不支持的媒體類型表明您發佈到Web服務代表的媒體類型(「應用程序/ x-WWW的形式,進行了urlencoded」)不是一個Web服務支持。我猜測Web服務期待'application/xml'表示。這一切都取決於你正在與之交談的網絡應用程序。

+0

很酷。讓我找出返回類型。謝謝! – 2012-01-06 14:40:02

相關問題