Http发送get、post、delete、put请求
1、GET请求会向数据库发索取数据的请求,从而来获取信息,该请求就像数据库的select操作一样,只是用来查询一下数据,不会修改、增加数据,不会影响资源的内容,即该请求不会产生副作用。无论进行多少次操作,结果都是一样的。
2、与GET不同的是,PUT请求是向服务器端发送数据的,从而改变信息,该请求就像数据库的update操作一样,用来修改数据的内容,但是不会增加数据的种类等,也就是说无论进行多少次PUT操作,其结果并没有不同。
3、POST请求同PUT请求类似,都是向服务器端发送数据的,但是该请求会改变数据的种类等资源,就像数据库的insert操作一样,会创建新的内容。几乎目前所有的提交操作都是用POST请求的。
4、DELETE请求顾名思义,就是用来删除某一个资源的,该请求就像数据库的delete操作。
package com.ruoyi.common.tool;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
/**
* @author wjw
*/
public class HttpURLConnectionUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpURLConnectionUtil.class);
/**
* 向指定URL发送GET方法的请求
*
* @param url
* 发送请求的URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param,String token) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
if(token!=null){
conn.setRequestProperty("Authorization",token);
}
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
/**
* delete请求
* @param data
* @param url
* @param token
* @return
* @throws IOException
*/
public static String sendDelete(String data, String url, String token) throws IOException {
logger.info("请求参数:{}", data);
logger.info("请求url:{}", url);
CloseableHttpClient client = null;
HttpDeleteWithBody httpDelete = null;
String result = null;
try {
client = HttpClients.createDefault();
httpDelete = new HttpDeleteWithBody(url);
httpDelete.addHeader("Content-type", "application/json; charset=utf-8");
httpDelete.setHeader("Accept", "application/json; charset=utf-8");
httpDelete.setHeader("Authorization", token);
httpDelete.setEntity(new StringEntity(data));
CloseableHttpResponse response = client.execute(httpDelete);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
logger.info("请求结果:{}", result);
if (200 == response.getStatusLine().getStatusCode()) {
logger.info("DELETE方式请求远程调用成功.msg={}", result);
}
} catch (Exception e) {
logger.error("DELETE方式请求远程调用失败,errorMsg={}", e.getMessage());
} finally {
client.close();
}
return result;
}
/**
* put请求
* @param urlPath
* @param data
* @param token
* @return
*/
public static String sendPut(String data, String urlPath, String token) {
logger.info("请求参数:{}", data);
logger.info("请求url:{}", urlPath);
String result = null;
URL url = null;
HttpURLConnection httpurlconnection = null;
try {
url = new URL(urlPath);
httpurlconnection = (HttpURLConnection) url.openConnection();
httpurlconnection.setDoInput(true);
httpurlconnection.setDoOutput(true);
// 设置通用的请求属性
httpurlconnection.setRequestProperty("accept", "*/*");
httpurlconnection.setRequestProperty("connection", "Keep-Alive");
httpurlconnection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
httpurlconnection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
if (token != null) {
httpurlconnection.setRequestProperty("Authorization", token);
}
httpurlconnection.setRequestMethod("PUT");
httpurlconnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
if (StringUtils.isNotBlank(data)) {
httpurlconnection.getOutputStream().write(data.getBytes("UTF-8"));
}
httpurlconnection.getOutputStream().flush();
httpurlconnection.getOutputStream().close();
int code = httpurlconnection.getResponseCode();
if (code == 200) {
DataInputStream in = new DataInputStream(httpurlconnection.getInputStream());
int len = in.available();
byte[] by = new byte[len];
in.readFully(by);
result = new String(by, Charset.forName("UTF-8"));
logger.info("请求结果:{}", result);
in.close();
} else {
logger.error("请求地址:" + urlPath + "返回状态异常,异常号为:" + code);
}
} catch (Exception e) {
logger.error("访问url地址:" + urlPath + "发生异常", e);
} finally {
url = null;
if (httpurlconnection != null) {
httpurlconnection.disconnect();
}
}
return result;
}
public static void main(String[] args) {
//发送 GET 请求
/*String s=HttpURLConnectionUtil.sendGet("http://localhost:6144/Home/RequestString", "key=123&v=456");
System.out.println(s);*/
//发送 POST 请求 http://61.55.158.220:54778/handle-paas-api/login/v1
String param="{\n" +
"\"username\":\"nuode@nuodwl\",\n" +
"\"password\":\"3e856379df63de7c19be0f6580f9726c4ad5905303f9779f9be984d5eae207ee\",\n" +
"\"developUsername\":\"hljjcsundi\",\n" +
"\"developPassword\":\"6493f5041ed91a81e0e629d0770e4bed6a5c90f58e50682ffaf17333280f37ff\"\n" +
"}";
String sr=HttpURLConnectionUtil.sendPost("http://61.55.158.220:54778/handle-paas-api/login/v1", param,null);
System.out.println(sr);
JSONObject result = (JSONObject) JSONObject.parse(sr);
JSONObject data =(JSONObject) result.get("data");
String token = data.get("token").toString();
System.out.println(token);
}
}
HttpDelete的方法中本身并没有setEntity方法,所以需要自定义一个HttpDeleteWithBody类
package com.ruoyi.common.tool;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;
/**
* @author wjw
*/
public class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "DELETE";
@Override
public String getMethod(){
return METHOD_NAME;
}
public HttpDeleteWithBody(final String uri){
super();
setURI(URI.create(uri));
}
public HttpDeleteWithBody(final URI uri){
super();
setURI(uri);
}
public HttpDeleteWithBody(){
super();
}
}
需要引入的包如下:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.1</version>
</dependency>