我有以下方法:
package com.restfully.shop.services;
import java.io.*;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import com.restfully.shop.domain.*;
@Path("/customers")
public class CustomerResource {
private Map<Integer, Customer> customerDB = new ConcurrentHashMap<Integer, Customer>();
private AtomicInteger idCounter = new AtomicInteger();
@POST
@Consumes("application/xml")
public Response createCustomer(InputStream is) {
System.out.println("GOT in POST");
Customer customer = readCustomer(is);
customer.setId(idCounter.incrementAndGet());
customerDB.put(customer.getId(), customer);
System.out.println("Created customer " + customer.getId());
return Response.created(URI.create("/customers/" + customer.getId())).build();
}
@GET
@Path("{id}")
@Produces("application/xml")
public StreamingOutput getCustomer(@PathParam("id") int id) {
Customer cust = new Customer();
cust.setCity("New_york"); cust.setCountry("USA"); cust.setFirstName("Bill");
cust.setId(0); cust.setLastName("Klinton"); cust.setState("MA"); cust.setStreet("Lane st.");
cust.setZip("02610");
customerDB.put(cust.getId(), cust);
final Customer customer = customerDB.get(id);
if (customer == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return new StreamingOutput() {
public void write(OutputStream outputStream)
throws IOException, WebApplicationException {
outputCustomer(outputStream, customer);
}
};
}
@PUT
@Path("{id}")
@Consumes("application/xml")
public void updateCustomer(@PathParam("id") int id, InputStream is) {
System.out.println("GOT in PUT");
Customer update = readCustomer(is);
Customer current = customerDB.get(id);
if (current == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
current.setFirstName(update.getFirstName());
current.setLastName(update.getLastName());
current.setStreet(update.getStreet());
current.setState(update.getState());
current.setZip(update.getZip());
current.setCountry(update.getCountry());
}
protected void outputCustomer(OutputStream os, Customer cust) throws IOException {
PrintStream writer = new PrintStream(os);
writer.println("<customer id=\"" + cust.getId() + "\">");
writer.println("<first-name>" + cust.getFirstName() + "</first-name>");
writer.println("<last-name>" + cust.getLastName() + "</last-name>");
writer.println("<city>" + cust.getCity() + "</city>");
writer.println("<state>" + cust.getState() + "</state>");
writer.println("<zip>" + cust.getZip() + "</zip>");
writer.println("<country>" + cust.getCountry() + "</country>");
writer.println("</customer>");
}
protected Customer readCustomer(InputStream is) {
DocumentBuilder builder;
try {
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(is);
Element root = doc.getDocumentElement();
Customer cust = new Customer();
if (root.getAttribute("id") != null
&& !root.getAttribute("id").trim().equals("")) {
cust.setId(Integer.parseInt(root.getAttribute("id")));
}
NodeList nodes = root.getChildNodes();
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
if (element.getTagName().equals("first-name")) {
cust.setFirstName(element.getTextContent());
} else if (element.getTagName().equals("last-name")) {
cust.setLastName(element.getTextContent());
} else if (element.getTagName().equals("street")) {
cust.setStreet(element.getTextContent());
} else if (element.getTagName().equals("city")) {
cust.setCity(element.getTextContent());
} else if (element.getTagName().equals("state")) {
cust.setState(element.getTextContent());
} else if (element.getTagName().equals("zip")) {
cust.setZip(element.getTextContent());
} else if (element.getTagName().equals("country")) {
cust.setCountry(element.getTextContent());
}
}
return cust;
} catch (Exception e) {
throw new WebApplicationException(e, Response.Status.BAD_REQUEST);
}
}
}
以下测试客户端:
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
String req = "<customer>" +
"<first-name>Bill</first-name>" +
"<last-name>Burke</last-name>" +
"<street>256 Kilonrinne</street>" +
"<city>Boston</city>" +
"<state>MA</state>" +
"<zip>02115</zip>" +
"<country>USA</country>" +
"</customer>";
URL url = new URL("http://localhost:8080/customers");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/xml;charset=utf-8");
OutputStream os = con.getOutputStream();
os.write(req.getBytes());
os.flush();
System.out.println(con.getResponseCode());
System.out.println("Location:" + con.getHeaderField("Location"));
con.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
当我测试服务时 - 该服务似乎适用于该课程的@GET部分。但它不适用于此处给出的@ POST请求。 我怎样才能使它发挥作用?
答案 0 :(得分:1)
尝试放
@POST
@Produces(MediaType.WILDCARD)
@Consumes("application/xml")
在帖子功能面前。
答案 1 :(得分:0)
我不是java开发人员,但我认为您可以使用@FormParam
来读取POST数据。它可能有所帮助。请确保您使用的是“application / x-www-form-urlencoded”mime类型。
参考:http://docs.jboss.org/resteasy/docs/2.0.0.GA/userguide/html_single/index.html#_FormParam
答案 2 :(得分:0)
我也会说尝试返回包含流输出的javax.ws.rs.Response:
StreamingOutput so = new StreamingOutput() {
public void write(OutputStream outputStream)
throws IOException, WebApplicationException {
outputCustomer(outputStream, customer);
}
return Response
.ok(so, MediaType.APPLICATION_OCTET_STREAM)
.header("Content-Disposition", "attachment; file_name = " + ltd.getName())
.header("Content-Length", file_len);