我有一个简单的Java REST Web服务 -
@GET
@Path("/get1")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Status getstudent(Track track) {
System.out.println("GET1 title = " + track.getTitle());
System.out.println("GET1 singer = " + track.getSinger());
Status status = new Status();
status.setStatus_flag("success");
return status;
}
轨道
public class Track {
String title;
String singer;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSinger() {
return singer;
}
public void setSinger(String singer) {
this.singer = singer;
}
@Override
public String toString() {
return "Track [title=" + title + ", singer=" + singer + "]";
}
}
Python请求模块: -
import requests
title = {"title":"Best Songs","singer":"lucky"}
r = requests.get("http://localhost:8080/StudentService/rest/insert/get1",data=title)
print r.content
错误
<html><head></head><body>
<h1>HTTP Status 415 - Unsupported Media Type</h1>
<HR size="1" noshade="noshade">
<p><b>type</b> Status report</p>
<p><b>message</b> <u>Unsupported Media Type</u></p>
<p><b>description</b>
<u>The server refused this request because the request entity is
in a format not supported by the requested resource for the requested
method.
</u>
</p>
<HR size="1" noshade="noshade"><h3>Apache Tomcat/6.0.41</h3>
</body></html>
有没有办法创建实体对象并发送它?
答案 0 :(得分:1)
您需要使用params
发送网址参数;您正在尝试发送请求 body 。
您需要更改服务以接受表单参数:
@GET
@Path("/get1")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Status getstudent(
@FormParam("title") String title,
@FormParam("singer") String sing) {
System.out.println("GET1 title = " + title);
System.out.println("GET1 singer = " + singer);
Status status = new Status();
status.setStatus_flag("success");
return status;
}
现在您可以发送URL编码的参数:
params = {"title": "Best Songs", "singer": "lucky"}
r = requests.get(
"http://localhost:8080/StudentService/rest/insert/get1",
params=params)
答案 1 :(得分:0)
只需在标题中添加内容类型和接受即可。像:
headers = {"Content-Type": "application/json", "Accept": "application/json"}
r = requests.get("http://localhost:8080/StudentService/rest/insert/get1", data=title, headers=headers)