2012-11-09 27 views
1

我有以下方法:POST方法在JAX-RS不工作JERSEY

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

什麼埃羅? –

+0

沒有錯誤。該方法不啓動 - 服務器日誌中至少沒有錯誤。測試類的控制檯寫入 - 404 - NOT_FOUND,Location - NULL –

+0

您可以發佈整個資源類嗎?小技巧:我會使用Jersey(或任何其他)Restful客戶端。通常這些客戶端實現可以在服務的接口上工作。在你的情況下,我會採取它,因爲它最大限度地減少了可以做的失敗。像缺少接受的標題等。 –

回答

1

嘗試把

@POST  
@Produces(MediaType.WILDCARD) 
@Consumes("application/xml") 

在後期的功能的面前。

+0

它沒有幫助... –

+0

我似乎無法找到POST註釋...但@GET工作得很好。 –

+1

嘗試使用 - 公共響應createCustomer(字符串是) –

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);