大佬教程收集整理的这篇文章主要介绍了Java HTTP 415 JSON不支持的媒体类型错误,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
不确定原因,但是charset=utf8
从中 删除行con.setrequestProperty("Content-Type", "application/Json; charset=utf8")
解决了该问题。
我正在用JSON请求调用REST服务,它给出了http 415“不支持的媒体类型”错误。
请求内容类型设置为(“ 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.abc.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;
}
}
{“ type”:“ arl”,“ action”:“删除”,“ domain”:“ staging”,“ objects:” http://www.abc.com “}
以上是大佬教程为你收集整理的Java HTTP 415 JSON不支持的媒体类型错误全部内容,希望文章能够帮你解决Java HTTP 415 JSON不支持的媒体类型错误所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。