JAVA使用HttpClients发送带参数的POST、GET请求

JAVA使用HttpClients发送带参数的POST、GET请求

POST和GET请求

携带了类型为文件类型和String类型 的参数

请求代码如下:

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Properties;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSON;

/**
 * 
 * @author dqk
 * @data 2021年11月2日
 */
public class HttpClientUtils {

	//POST请求
	public static HashMap<String,Object> upload2server(CommonsMultipartFile file,String dirPath) throws IOException {
		Properties prop = getPropertiesParam("dbconfig.properties");
		//从配置文件中获取请求的ip+端口
		String fileServerIp = prop.getProperty("fileServerIp");
		//拼接URL
		String url = "http://"+fileServerIp+"/upload/uploadFile";
		//创建一个默认的HttpClient
		CloseableHttpClient httpClient = HttpClients.createDefault();
		//用于存相应信息
		HashMap<String,Object> map =new HashMap<>();
		try {
			//以post方式请求网页
			HttpPost httpPost = new HttpPost(url);
			String fileName = file.getOriginalFilename().replaceAll(" ", "");
			//String fileName = file.getOriginalFilename();
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
	         builder.setCharset(Charset.forName("utf-8"));
	         //builder.seContentType(ContentType.APPLICATION_JSON);
	         builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题
	         builder.addBinaryBody("file", file.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
	         //builder.addTextBody("filePath", path);// 类似浏览器表单提交,对应input的name和value
	         ContentType contentType = ContentType.create("text/plain", "UTF-8");
	         StringBody pathStringBody = new StringBody(fileName,contentType);
	         StringBody dirPathStringBody = new StringBody(dirPath,contentType);
	         builder.addPart("fileName", pathStringBody);
	         builder.addPart("dirPath", dirPathStringBody);
	         HttpEntity entity = builder.build();
	         httpPost.setEntity(entity);
	         HttpResponse execute = httpClient.execute(httpPost);// 执行提交
	         String entityStr = EntityUtils.toString(execute.getEntity(),"UTF-8");
	         //将响应信息存储到map
	         map = JSON.parseObject(entityStr, HashMap.class);
		}catch(Exception e){
			e.printStackTrace();
			map.put("code", false);
			map.put("msg", "连接文件服务器错误!");
		}finally {
			// 当不再需要HttpClient实例时,关闭连接管理器以确保释放所有占用的系统资源
			httpClient.close();
		}
		return map;
	}
	//GET请求
	public static HashMap<String,Object> delFile(String path) throws IOException {
		Properties prop = getPropertiesParam("dbconfig.properties");
		String fileServerIp = prop.getProperty("fileServerIp");
		//拼接URL
		String url = "http://"+fileServerIp+"/del/delFile";
  		 // 创建Httpclient对象
         CloseableHttpClient httpclient = HttpClients.createDefault();
         // 定义请求的参数
         URI uri = null;
		try {
			uri = new URIBuilder(url).setParameter("path", path).build();
		} catch (URISyntaxException e1) {
			e1.printStackTrace();
		}
         // 创建http GET请求
         HttpGet httpGet = new HttpGet(uri);
         //response 对象
         CloseableHttpResponse response = null;
         HashMap<String,Object> map =new HashMap<>();
         try {
        	 //设置请求头部编码
        	 httpGet.setHeader(new BasicHeader("Content-Type", "application/json; charset=utf-8"));
        	 //设置返回编码
        	 httpGet.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
             // 执行http get请求
             response = httpclient.execute(httpGet);
             String entityStr = EntityUtils.toString(response.getEntity(),"UTF-8");
 			 map = JSON.parseObject(entityStr, HashMap.class);
         }catch(Exception e){
 			e.printStackTrace();
 			map.put("code", false);
 			map.put("msg", "连接文件服务器错误!");
 		}finally {
             if (response != null) {
                 response.close();
             }
             httpclient.close();
         }
         return map;
     }
	
	public static Properties getPropertiesParam(String name) throws IOException {
		Properties prop = PropertiesLoaderUtils.loadAllProperties(name);
		return prop;
		
	}
}

对应的post请求的接口

import java.io.File;
import java.io.IOException;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.file.resoult.AjaxResoult;

@RequestMapping("/upload")
@RestController
public class UploadFileController {

	@PostMapping("/uploadFile")
	public AjaxResoult uploadFile1(@RequestParam(value = "file",required=false) MultipartFile file,String fileName,String dirPath) {
		AjaxResoult ajaxResoult = new AjaxResoult();
		return ajaxResoult;
	}
	
}

对应的GET请求的接口

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.file.resoult.AjaxResoult;

@RequestMapping("/del")
@RestController
public class DeleteFileController {

	@GetMapping("/delFile")
	public AjaxResoult delFile(String path) {
		AjaxResoult ajaxResoult = new AjaxResoult();
		return ajaxResoult;
	}
	}

结束!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值