如何使用HttpClient发送帖子请求

时间:2012-08-02 17:50:09

标签: java eclipse httpclient

有没有人知道如何使用HttpClient库在Java Eclipse中使用post请求更新页面?目前这就是我所拥有的,但是什么时候 我执行它我得到一个页面未找到错误:

public void update() {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://examplepage.xml");
    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("_action", "<BasicPage><title>New Title</title></BasicPage>"));
        nameValuePairs.add(new BasicNameValuePair("_method", "post"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        String info = (""+EntityUtils.toString(entity));
        System.out.println(info);
        System.out.println(response.getEntity().getContent());
        System.out.println(response);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}

1 个答案:

答案 0 :(得分:0)

您的代码看起来很好。检查页面URI或别名“examplepage.xml”是否确实存在或映射。还要检查它是否可以接受POST请求。