POST方法用来向目的服务器发出请求,要求它接受被附在请求后的实体,并把它当作请求队列(Request-Line)中请求URI所指定资源的附加新子项。POST被设计成用统一的方法实现下列功能:
- 对现有资源的注释(Annotation of existing resources)
- 向电子公告栏、新闻组,邮件列表或类似讨论组发送消息
- 提交数据块,如将表单的结果提交给数据处理过程
- 通过附加操作来扩展数据库
有两个主要步骤使用POST方法:首先提供的数据请求,,其次阅读服务器的响应。
package http.yang; import java.io.IOException; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.methods.*; import org.apache.commons.httpclient.params.*; public class HttpPostSimple { /** * @param args * @throws IOException * @throws HttpException */ public static void main(String[] args) throws HttpException, IOException { // TODO Auto-generated method stub HttpClient httpClient = new HttpClient(); String url = "http://jakarata.apache.org"; PostMethod postMethod = new PostMethod(url); // 填入各个表单域的值 NameValuePair[] data = { new NameValuePair("user", "joe"), new NameValuePair("password", "bloggs") };// 将表单的值放入postMethod中 postMethod.setRequestBody(data);// 执行postMethodint statusCode = httpClient.executeMethod(postMethod);// HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发// 301或者302 if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { // 从头中取出转向的地址 Header locationHeader = postMethod.getResponseHeader("location"); String location = null; if (locationHeader != null) { location = locationHeader.getValue(); System.out.println("The page was redirected to:" + location); } else { System.err.println("Location field value is null."); } return; }}}
示例2
参考资料:
package yang.httpclient;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class PostMethodExample {
public static void main(String args[]) {
HttpClient client = new HttpClient();
client.getParams().setParameter("http.useragent", "Test Client");
BufferedReader br = null;
PostMethod method = new PostMethod("http://search.yahoo.com/search");
method.addParameter("p", "\"java2s\"");
try{
int returnCode = client.executeMethod(method);
if(returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
System.err.println("The Post method is not implemented by this URI");
// still consume the response body
method.getResponseBodyAsString();
} else {
br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
String readLine;
while(((readLine = br.readLine()) != null)) {
System.err.println(readLine);
}
}
} catch (Exception e) {
System.err.println(e);
} finally {
method.releaseConnection();
if(br != null) try { br.close(); } catch (Exception fe) {}
}
}
}
参考资料:
- Commons logging包含了各种各样的日志API的实现,读者可以通过站点http://jakarta.apache.org/commons/logging/得到详细的内容
- Commons codec包含了一些一般的解码/编码算法。包含了语音编码、十六进制、Base64和URL编码等,通过http://jakarta.apache.org/commons/codec/可以得到详细的内容
- rfc2616是关于HTTP/1.1的文档,可以在http://www.faqs.org/rfcs/rfc2616.html上得到详细的内容,另外rfc1945是关于HTTP/1.0的文档,通过http://www.faqs.org/rfcs/rfc1945.html可以得到详细内容