使用Python请求调用Java网络服务
我有一个简单的Java REST网络服务 -
@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>
有没有办法创建实体对象并发送它?
2 个回答
0
只需要在请求的头部添加内容类型和接受类型。比如:
headers = {"Content-Type": "application/json", "Accept": "application/json"}
r = requests.get("http://localhost:8080/StudentService/rest/insert/get1", data=title, headers=headers)
1
你需要使用 params
来发送网址参数;你现在试图发送的是请求的 主体。
你需要修改你的服务,以便它可以接受表单参数:
@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;
}
现在你可以发送网址编码的参数了:
params = {"title": "Best Songs", "singer": "lucky"}
r = requests.get(
"http://localhost:8080/StudentService/rest/insert/get1",
params=params)