目录
1. Post请求介绍
在客户端与服务器之间进行请求响应时,除了Get请求以外,Post请求也是另外一种最常见的请求。Post一般向指定的资源提交要被处理的数据。Get请求参数一般写在URL上,Post通过表单提交不会显示在URL上,更具有隐蔽性。
有关Post请求的一些注释如下:
1. Post请求不会被缓存。
2. Post请求不会保留在浏览器历史记录中。
3. Post请求不能被收藏成书签。
4. Post请求对数据长度没有要求。
2. RESTful的Post请求
1. 通过HttpsClients构建HTTP客户端。
2. 通过Post请求来实例化HttpPost.
3. 使用String形式构建Post请求。
4. 通过http客户端执行Post请求并且处理响应结果。
5. 捕捉异常。
package http;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
/**
* author 大力pig
*/
public class TestRestPost {
public static void main(String[] args) {
//创建HTTP默认的客户端
CloseableHttpClient client = HttpClients.createDefault();
//实例化HPPT post请求
HttpPost httpPost1 = new HttpPost("http://localhost:8080/mobilePhone");
//定义传入的entiry, 并且类型为Json格式
StringEntity stringEntity = new StringEntity("{\"brand\":\"Motorola\",\"model\":\"moto Z Play\", \"os\":\"ANDROID\"}", ContentType.APPLICATION_JSON);
httpPost1.setEntity(stringEntity);
CloseableHttpResponse response = null;
try {
response = client.execute(httpPost1);
System.out.println(EntityUtils.toString(response.getEntity()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
结果
3. SOAP请求,未完待续。