【发布时间】:2014-04-29 06:33:36
【问题描述】:
我正在使用 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"}
【问题讨论】:
-
请用
requestJson.toString()的值更新您的问题 -
requestJson.toString 的值为:{"type":"arl","action":"remove","domain":"staging","objects":"abc.com"}
-
服务器部分写了吗?如果您对 Postman(Chrome 扩展程序,谷歌它)执行相同的请求,它是否有效?也许服务器出于某种原因不接受 JSON 内容类型?
-
是的,我使用soapUI进行了测试。我发送了完全相同的请求,包括 json 并从服务器获得了成功的响应。
-
@joscarsson,自 2017 年 3 月 14 日起,不推荐使用 Postman chrome 扩展。他们转移到本机应用程序。这是他们的博文:http://blog.getpostman.com/2017/03/14/going-native/
标签: java json http-status-code-415