如何在客户端访问post java方法

时间:2013-05-30 05:02:03

标签: java rest jax-rs restful-url

我需要小帮助,我是新手在java中创建rest方法但我发现它并创建一个rest方法。我有一个包含不同方法的类。在这里我的班级

@Path("/WebServices ")
public class WebServices {
@POST
@Path("/SourceCreateService")
@Consumes("multipart/related")
@Produces("text/plain")
public String sourceCreateService(@QueryParam("sourceTiltle") String sourceTiltle, @QueryParam("xml") String xml) {
return "name";
}
}

And now i have to access this method in another class,I can use this code to access this method in this class,

try{
URL url = new URL("http://localhost:8080/web/WebServices/SourceCreateService?sourceTiltle=sdds&xml="XML");

URLConnection conn = url.openConnection();
conn.setDoOutput(true); // Triggers POST.
// conn.setDoInput(true);
conn.setRequestProperty("Accept-Charset", charset);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);

BufferedWriter out =
new BufferedWriter( new OutputStreamWriter( conn.getOutputStream() ) );
out.write("username=name\r\n");
out.flush();
out.close();
BufferedReader in =
new BufferedReader( new InputStreamReader( conn.getInputStream() ) );

}catch(IOException e){
system.out.println(""+e);

}

when  i call this method i got this error,

java.io.IOException: Server returned HTTP response code: 505 for URL:

I put debugpoint in web service method also,but it not come to that method,it directly throws exception here,so my question is that my webservice methog is right and kindly tell me what is the wrong in my code and my URL

web.xml中是否有任何配置

1 个答案:

答案 0 :(得分:0)

由于您发布了对数据进行form-url编码,因此必须使用@FormParam而不是@QueryParam

来注释方法参数。
@Path("/WebServices ")
public class WebServices {
    @POST
    @Path("/SourceCreateService")
    @Consumes("multipart/related") @Produces("text/plain")
    public String sourceCreateService(@FormParam("sourceTiltle") String sourceTiltle,     
                                      @QueryParam("xml") String xml) {
            return "name";
    }
}

请参阅此问题/答案:jQuery not POSTing URL arguments to Jersey service?