java:httppost在rubyonrails应用程序中创建新的“ride”

a9wyjsp7  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(275)

我的问题非常类似于java:httppost在rubyonrails应用程序中创建新的“产品”
我有一个表单,我想“发布”到一个看起来像这样的表单

Offer:<br /> 
<input id="ride_togive" name="ride[togive]" size="30" type="text" /> 
</p> 
<p> 
Request for Offer:<br /> 
<input id="ride_totake" name="ride[totake]" size="30" type="text" /> 
</p>

我的java代码如下

DefaultHttpClient client = new DefaultHttpClient();

         HttpPost post = new HttpPost("http://172.16.60.129:3000/rides");

     // Configure the form parameters
        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("ride_totake", "Ride to Vail"));
        nvps.add(new BasicNameValuePair("ride_togive", "$20"));

        post.addHeader("Content-Type","application/json");

        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        HttpResponse response = null;
        try {
            response = client.execute(post);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        HttpEntity entity = response.getEntity();
        System.out.println("form get: " + response.getStatusLine());
        if (entity != null) {
            try {
                entity.consumeContent();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

下面是ror控制台的输出

Processing RidesController#create (for 172.16.60.1 at 2009-11-04 22:22:52) [POST]
Parameters: {"_json"=>"totake=Ride+to+Vail&togive=%2420"}
Ride Columns (0.6ms)   SHOW FIELDS FROM `rides`
SQL (0.1ms)   BEGIN
Ride Create (0.3ms)   INSERT INTO `rides` (`isoffer`, `togive`, `howlong`, `updated_at`,       `totake`, `created_at`) 
VALUES(NULL, NULL, 0, '2009-11-05 05:22:52', NULL, '2009-11-05    05:22:52')
SQL (0.0ms)   COMMIT
Redirected to http://172.16.60.129:3000/rides
Completed in 9ms (DB: 1) | 302 Found [http://172.16.60.129/rides]

我想我真正的问题是如何在java中处理ror变量?

eoigrqb6

eoigrqb61#

在html输入标记中使用名称而不是id。在您的示例中,它们是“ride[togive]”和“ride[totake]”。
在我的ror项目上工作的示例java代码。使用httpclient 3.1

PostMethod post = new PostMethod("http://localhost:3000/projects");
NameValuePair[] data = {
  new NameValuePair("project[name]", "from java"),
  new NameValuePair("project[life_cycle_id]", "5")
};
post.setRequestBody(data);
// execute method and handle any error responses.

new HttpClient().executeMethod(post);

从ror控制台:

Processing ProjectsController#create (for 127.0.0.1 at 2009-11-04 22:07:39) [POS
T]
  Parameters: {"project"=>{"name"=>"from java", "life_cycle_id"=>"5"}}

相关问题