Java代码发送Http的GET和POST请求
1、HTTP中GET和POST的区别
⾸先要了解下GET和POST的区别。
HTTP定义了4种与服务器交互⽅法:GET,POST,PUT,DELETE。URL全称是资源描述符,可以这样认为:⼀个URL地址,它⽤于描述⼀个⽹络上的资源,⽽HTTP中的GET,POST,PUT,DELETE可以理解为就对应着对这个资源的查,改,增,删4个操作。GET⼀般⽤于获取/查询资源信息,⽽POST⼀般⽤于更新资源信息。GET和POST的区别主要从以下⼏个⽅⾯理解:
⽤途
根据HTTP规范,GET⽤于信息获取,⽤于获取信息⽽⾮修改信息。GET请求⼀般不应产⽣副作⽤。它仅仅是获取资源信息,就像数据库查询⼀样,不会修改,增加数据,不会影响资源的状态。对同⼀URL的多个请求应该返回同样的结果。 POST可能修改变服务器上的资源的请求。
请求数据的传递⽅式
GET请求的数据会附在URL之后(就是把数据放置在HTTP协议头中),以?分割URL和传输数据,参数之间以&相连,如:buy.jsp?
product=apple&amount=1111&verify=%E4%BD%A0%E5%A5%BD。如果数据是英⽂字母或者数字,原样发送,如果是空格,转换为+,如果是中⽂或者其他字符,则直接把字符串⽤BASE64加密,得出如:%E4%BD%A0%E5%A5%BD,其中%XX中的XX为该符号以16进制表⽰的ASCII。⽽POST把提交的数据则放置在是HTTP包的包体中。
提交数据的⼤⼩限制
GET⽅式提交的数据最多只能是1024字节(GET请求中参数是附在url后⾯的,实际上这个长度是url长度的要求)。理论上POST没有限制,可传较⼤量的数据。这⼀点可以先简单这么理解。
安全性
POST的安全性要⽐GET的安全性⾼。⽐如,通过GET提交数据,⽤户名和密码将明⽂出现在URL上。
阶乘函数用递归定义
常见场景
在FORM表单中,Method默认为"GET"。在浏览器地址栏中输⼊url发⽣请求都是GET,如果要发送POST请求就需要通过提交form表单来完成。
2、Java代码发送GET和POST请求
Java中应该有好多种⽅式,可以发送GET和POST请求。这⾥介绍两种:通过HttpURLConnection和通过Apache HttpClient库。
2.1 通过HttpURLConnection发送GET和POST请求
这种⽅式基本上算是java原⽣的,不需要导⼊任何jar包依赖就可以运⾏。代码如下:
import java.io.*;
import java.HttpURLConnection;
import java.MalformedURLException;
import java.URL;
/**
* Created by chengxia on 2018/12/4.
*/
public class HttpURLConnectionDemo {
public String doPost(String URL){
OutputStreamWriter out = null;
图片素材免费网站BufferedReader in = null;
StringBuilder result = new StringBuilder();
HttpURLConnection conn = null;
try{
URL url = new URL(URL);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
//发送POST请求必须设置为true
conn.setDoOutput(true);
conn.setDoInput(true);
//设置连接超时时间和读取超时时间
conn.setConnectTimeout(30000);
conn.setReadTimeout(10000);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
//获取输出流
out = new OutputStream());
String jsonStr = "{\"qry_by\":\"name\", \"name\":\"Tim\"}";
out.write(jsonStr);
out.flush();
out.close();
//取得输⼊流,并使⽤Reader读取
if (200 == ResponseCode()){
in = new BufferedReader(new InputStream(), "UTF-8"));                String line;
while ((line = in.readLine()) != null){
result.append(line);
System.out.println(line);
}
}else{
System.out.println("ResponseCode is an error code:" + ResponseCode());            }
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(out != null){
out.close();
}
if(in != null){
in.close();
}
}catch (IOException ioe){
ioe.printStackTrace();
}
}
String();
}
public String doGet(String URL){
HttpURLConnection conn = null;
InputStream is = null;
BufferedReader br = null;
StringBuilder result = new StringBuilder();
try{
/
/创建远程url连接对象
URL url = new URL(URL);
//通过远程url连接对象打开⼀个连接,强转成HTTPURLConnection类
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
//设置连接超时时间和读取超时时间
conn.setConnectTimeout(15000);
conn.setReadTimeout(60000);
conn.setRequestProperty("Accept", "application/json");
//发送请求
/
/通过conn取得输⼊流,并使⽤Reader读取
if (200 == ResponseCode()){
is = InputStream();
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String line;
while ((line = br.readLine()) != null){
result.append(line);
System.out.println(line);
}
}else{
System.out.println("ResponseCode is an error code:" + ResponseCode());            }
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(br != null){
br.close();
}
if(is != null){
is.close();
}
}catch (IOException ioe){
ioe.printStackTrace();
}
conn.disconnect();
}
String();
}
public static void main(String[] args) throws Exception {
HttpURLConnectionDemo http = new HttpURLConnectionDemo();
System.out.println("Testing 1 - Do Http GET request");
http.doGet("localhost:8080");
System.out.println("\nTesting 2 - Do Http POST request");
http.doPost("localhost:8080/json");
}
}
运⾏的输出如下:
Testing 1 - Do Http GET request
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello Word!</h1>
</body>
</html>
Testing 2 - Do Http POST request
[{name:'Kobe', team:‘Lakers’},{name:'Tim', team:‘Spurs’}]
Process finished with exit code 0
从这个例⼦的代码中就可以看出,GET请求向服务器发送的数据,都放在url中,这样在发送请求是不
⽤向请求正⽂中写⼊数据。⽽POST请求在发送时,必须先将发送的数据,写⼊到请求正⽂中。下⾯的apache httpclient实现中,也能看出这个区别。
2.2 通过Apache HttpClient发送GET和POST请求
这⾥需要⽤到Apache HttpClient的依赖包,所以要先去下载依赖的jar包:
Apache官⽹下载依赖jar包
解压之后,将lib⽬录下所有的jar包⽂件,导⼊到⼯程的依赖⽬录(我曾经天真的以为只需要⼀个httpclient-4.5.6.jar,然⽽在编译时各种报错,全部导⼊到就好了):
下载的jar包解压之后
全部导⼊到⼯程的依赖⽬录中
react 阮一峰最后,Java代码如下:
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.fig.RequestConfig;
import org.apache.hods.CloseableHttpResponse;
import org.apache.hods.HttpGet;
import org.apache.hods.HttpPost;
import org.ity.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;
/**
* Created by chengxia on 2018/12/5.
*/
public class ApacheHttpClientDemo {
public String doGet(String url){
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
String result = "";
try{
//通过默认配置创建⼀个httpClient实例
httpClient = ateDefault();
//创建httpGet远程连接实例
HttpGet httpGet = new HttpGet(url);
//httpGet.addHeader("Connection", "keep-alive");
//设置请求头信息
httpGet.addHeader("Accept", "application/json");
//配置请求参数
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(35000) //设置连接主机服务超时时间
.setConnectionRequestTimeout(35000)//设置请求超时时间
.setSocketTimeout(60000)//设置数据读取超时时间
.build();
//为httpGet实例设置配置
httpGet.setConfig(requestConfig);
//执⾏get请求得到返回对象
response = ute(httpGet);
//通过返回对象获取返回数据
HttpEntity entity = Entity();
写出冒泡算法的java代码实现
//通过EntityUtils中的toString⽅法将结果转换为字符串,后续根据需要处理对应的reponse code            result = String(entity);
System.out.println(result);
}catch (ClientProtocolException e){
e.printStackTrace();
}catch (IOException ioe){
ioe.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}finally {
//关闭资源
if(response != null){
try {
response.close();
}catch (IOException ioe){
ioe.printStackTrace();
}
}
if(httpClient != null){
try{
httpClient.close();
}catch (IOException ioe){
ioe.printStackTrace();
}
}
}
return result;
}
public String doPost(String url){
/
/创建httpClient对象
CloseableHttpClient httpClient = ateDefault();
CloseableHttpResponse response = null;
String result = "";
try{
//创建http请求
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json");
//创建请求内容
String jsonStr = "{\"qry_by\":\"name\", \"name\":\"Tim\"}";
StringEntity entity = new StringEntity(jsonStr);
httpPost.setEntity(entity);
response = ute(httpPost);
result = Entity(),"utf-8");
System.out.println(result);
}catch (Exception e){
e.printStackTrace();
}finally {
//关闭资源
if(response != null){
try {
response.close();
jsp中文全称}catch (IOException ioe){
ioe.printStackTrace();
}
}
if(httpClient != null){
try{
httpClient.close();
}catch (IOException ioe){
ioe.printStackTrace();
}
}
}
return result;
}
public static void main(String[] args) throws Exception {
ApacheHttpClientDemo http = new ApacheHttpClientDemo();
System.out.println("Testing 1 - Do Http GET request");
http.doGet("localhost:8080");
System.out.println("\nTesting 2 - Do Http POST request");
http.doPost("localhost:8080/json");
}
}
述职报告ppt模板范文
由于是向相同的url发送请求,这个例⼦的输出和前⾯的例⼦是⼀样的。
参考
分别介绍了Standard HttpURLConnection和Apache HttpClient library发送http请求的⽅法,有例⼦。
这个链接中提到了get请求参数通过url传递,post通过正⽂传递。
In a GET request, the parameters are sent as part of the URL.
In a POST request, the parameters are sent as a body of the request, after the headers.
⼀个通过HTTPURLconnection发送json数据的例⼦
作者:SpaceCat
链接:www.jianshu/p/117264481886
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,⾮商业转载请注明出处。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。