如何使用httpclient发送url帖子



我使用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) {
    ....
    }

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

请帮我解决这个问题

这取决于服务可以接受什么样的内容。Xml/json/什么?

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

如何进行封送取决于您的项目。有很多库可以做到这一点,我想JAXB是最流行的。

相关内容

  • 没有找到相关文章

最新更新