如何使用httpclient发送url帖子

时间:2013-04-12 07:12:44

标签: java spring-mvc reflection apache-httpclient-4.x

我使用httpclient登录我的项目,如下所示:

public void login(String username,String password){
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://localhost:8080/j_spring_security_check");
        try {
          List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
          nameValuePairs.add(new BasicNameValuePair("j_username", username));
          nameValuePairs.add(new BasicNameValuePair("j_password", password));

          post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
          HttpResponse response = client.execute(post);

          BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

我使用上面的内容如下:

HttpClientRequests httpRequest = new HttpClientRequests();
httpRequest.login("mayank","hexgen");

现在我想发送一个POST方法请求,如下所示:

@RequestMapping(method = RequestMethod.POST, value = "/trade/createrequisition")
    public @ResponseBody
    void createRequisition(@RequestBody CreateRequisitionRO[] request,
            @RequestHeader("validateOnly") boolean validateOnly) {
....
}

所以我创建了如下反射:

HttpClientRequests httpRequest = new HttpClientRequests();
        Class[] paramString = new Class[1]; 
        paramString[0] = String.class;

        Class parames = CreateRequisitionRO[].class;

        CreateRequisitionRO[] roRqequest = new CreateRequisitionRO[1];
        boolean istrueOrFalse=true;


        Class booleanVal ;  
        booleanVal = Boolean.TYPE;

        Class cls;
        try {
            cls = Class.forName("com.hexgen.api.facade.HexgenWebAPI");

            Method method = cls.getDeclaredMethod("createRequisition", parames,booleanVal);

            RequestMapping methodRequestMappingAnnotation = method.getAnnotation(RequestMapping.class);
            RequestMethod[] methods = methodRequestMappingAnnotation.method();
            String[] mappingValues = methodRequestMappingAnnotation.value();
            //String methodType = methods[0].name();
            //String url = mappingValues[0];

            httpRequest.login("mayank","hexgen");

        }catch(Exception ex){
            ex.printStackTrace();
        } 

现在在此httpRequest.login("mayank","hexgen");之后如何发送请求以访问以下方法:

@RequestMapping(method = RequestMethod.POST, value = "/trade/createrequisition")
        public @ResponseBody
        void createRequisition(@RequestBody CreateRequisitionRO[] request,
                @RequestHeader("validateOnly") boolean validateOnly) {
    ....
    }

所以

我可以以编程方式登录系统,但在成功登录后无法调用。

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

这取决于服务可以接受的内容类型。 XML / JSON /不管?

我看到你得到了你必须通过反思发布的地址。您应该发布到该地址的内容是编组为json / xml(?)的CreateRequisitionRO数组。一旦你将它们编组,只需发送带有该conent集作为请求实体的帖子消息。然后,服务器端应该解组请求内容并调用createRequisition()处理程序方法。

编组如何完成取决于您的项目。有很多库,我猜JAXB是最普遍的。