我用一个JSON请求调用一个REST服务,它的响应是一个HTTP 415 "Unsupported Media Type"错误.

请求内容类型设置为("Content-Type", "application/json; charset=utf8").

如果我不在请求中包含JSON对象,它可以很好地工作.我正在使用JSON的google-gson-2.2.4库.

我试着使用了几个不同的库,但没有什么不同.

谁能帮我解决这个问题吗?

以下是我的代码:

public static void main(String[] args) throws Exception
{

    JsonObject requestJson = new JsonObject();
    String url = "xxx";

    //method call for generating json

    requestJson = generateJSON();
    URL myurl = new URL(url);
    HttpURLConnection con = (HttpURLConnection)myurl.openConnection();
    con.setDoOutput(true);
    con.setDoInput(true);

    con.setRequestProperty("Content-Type", "application/json; charset=utf8");
    con.setRequestProperty("Accept", "application/json");
    con.setRequestProperty("Method", "POST");
    OutputStream os = con.getOutputStream();
    os.write(requestJson.toString().getBytes("UTF-8"));
    os.close();


    StringBuilder sb = new StringBuilder();  
    int HttpResult =con.getResponseCode();
    if(HttpResult ==HttpURLConnection.HTTP_OK){
    BufferedReader br = new BufferedReader(new   InputStreamReader(con.getInputStream(),"utf-8"));  

        String line = null;
        while ((line = br.readLine()) != null) {  
        sb.append(line + "\n");  
        }
         br.close(); 
         System.out.println(""+sb.toString());  

    }else{
        System.out.println(con.getResponseCode());
        System.out.println(con.getResponseMessage());  
    }  

}
public static JsonObject generateJSON () throws MalformedURLException

{
   String s = "http://www.example.com";
        s.replaceAll("/", "\\/");
    JsonObject reqparam=new JsonObject();
    reqparam.addProperty("type", "arl");
    reqparam.addProperty("action", "remove");
    reqparam.addProperty("domain", "staging");
    reqparam.addProperty("objects", s);
    return reqparam;

}
}

requestJson.toString()的值为:

{"type":"arl","action":"remove","domain":"staging","objects":"http://www.example.com"}

推荐答案

不确定原因,但从con.setRequestProperty("Content-Type", "application/json; charset=utf8")中删除第charset=utf8行解决了问题.

Java相关问答推荐

Maven Google Sheets版本问题

我应该避免在Android中创建类并在运行时编译它们吗?

如何在访问完所有文件后加入所有线程?

CAMEL 4中的SAXParseException

为什么我要创建一个单独的互斥体/锁对象?

现场观看Android Studio中的变化

滚动视图&不能在alert 对话框中工作(&Q;&Q;)

将不受支持的时区UT重写为UTC是否节省?

Mapstruct不能正确/完全映射属性

JNI:将代码打包成自包含的二进制文件

STREAMS减少部分结果的问题

除0错误/抱歉我的句子是PT

判断重复的两个二维表算法?

为什么项目名称出现在我的GET请求中?

将BlockingQueue+守护程序线程替换为执行器

SonarQube在合并升级到java17后对旧代码提出错误

双对象供应商

窗口启动后不久,从java.awt.Graphics disapear创建的矩形

睡眠在 Spring Boot 中

如何在 lambda 中烘焙值