HttpClientを使用してHTTPをシミュレートし、POSTまたはGETリクエストを送信します

Java開発では、サービス間で呼び出しを行うには、HttpClientを使用してHTTPリクエストを送信する必要があります。以下は、Javaを使用してPOSTまたはGETリクエストを送信するHTTPをシミュレートするコードです。

1.HTTP依存関係をpom.xmlにインポートします

    <!-- HTTP请求依赖 -->
	<dependency>
		<groupId>org.apache.httpcomponents</groupId>
		<artifactId>httpclient</artifactId>
		<version>4.5.2</version>
	</dependency>
	<!-- json依赖 -->
	<dependency>
		<groupId>com.alibaba</groupId>
		<artifactId>fastjson</artifactId>
		<version>1.2.47</version>
	</dependency>

2. Postまたはgetリクエストを送信するときは、
パラメーターを渡す必要がある場合に注意してください。テキストパラメーターはStringEntityを使用し、パラメーターはjsonオブジェクトに配置され、ファイルパラメーターはMultipartEntityBuilderを使用します。

package com.dascom.smallroutine.utils;
import java.io.IOException;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
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.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class HttpClientUtil {
    
    
	
    //日志输出
    private static Logger logger = LogManager.getLogger(HttpClientUtil.class);
	
	/**
	 * 发送get请求 调用这个方法
	 * @param url
	 * @return str	//返回请求的内容
	 * @throws Exception
	 */
	public static String doGet(String url){
    
    
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();;
		String returnValue = null;
		// 创建http GET请求
		HttpGet httpGet = new HttpGet(url);
		CloseableHttpResponse response = null;
		try {
    
    
			//执行请求
			response = httpClient.execute(httpGet);
			//判断返回状态是否为200
			if(response.getStatusLine().getStatusCode() == 200) {
    
    
				//请求体内容
				returnValue = EntityUtils.toString(response.getEntity(), "UTF-8");
				return returnValue;
			}
		} catch (ClientProtocolException e) {
    
    
			e.printStackTrace();
		} catch (IOException e) {
    
    
			e.printStackTrace();
		} finally {
    
    
			if (response != null) {
    
    
				try {
    
    
					response.close();
				} catch (IOException e) {
    
    
					logger.error("response关闭失败!");
					e.printStackTrace();
				}
			}
			try {
    
    
				httpClient.close();
			} catch (IOException e) {
    
    
				logger.error("httpClient关闭失败!");
				e.printStackTrace();
			}
		}
		return returnValue;
	}
	
	/**
	 * 发送Post请求 调用这个方法 带json参数
	 * @param url	要请求的地址
	 * @param json	要发送的json格式数据
	 * @return 返回的数据
	 */
	public static String doPostWithJson(String url,JSONObject json){
    
    
		String returnValue = null;
        CloseableHttpClient httpclient = null;
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
    
    
            //创建httpclient对象
        	httpclient = HttpClients.createDefault();
            //创建http POST请求
            HttpPost httpPost = new HttpPost(url);
            //文本参数用StringEntity,文件参数用MultipartEntityBuilder
        	StringEntity requestEntity = new StringEntity(json.toJSONString(),"utf-8");
        	requestEntity.setContentEncoding("UTF-8");
        	httpPost.setHeader("Content-type","application/json");//请求头
        	httpPost.setEntity(requestEntity);
        	//发送请求,获取返回值
        	returnValue = httpclient.execute(httpPost,responseHandler);
		}catch (Exception e) {
    
    
			logger.error("发送post请求失败!"+e.getMessage());
		}finally {
    
    
			try {
    
    
				httpclient.close();
			} catch (IOException e) {
    
    
				logger.error("httpclient关闭失败!"+e.getMessage());
			}
		}
        return returnValue;
	}
}

3.テスト

public class Test {
    
    
	
	public static void main(String[] args) {
    
    
		//GET请求访问
		HttpClientUtil.doGet("http://baidu.com");
		//POST请求访问
		JSONObject json = new JSONObject();
		json.put("data", "成功");//参数
		HttpClientUtil.doPostWithJson("http://baidu.com", json);
	}
}

ファイルパラメータインターフェイスをリクエストする場合の例は次のとおりです

ここに画像の説明を挿入
コード

package com.example.demo.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONObject;
@RestController
@RequestMapping("/v1.0")
public class PrintController {
    
    
	//日志输出
    private static Logger logger = LogManager.getLogger(PrintController.class);
	@RequestMapping(value="/monitprint",method=RequestMethod.POST,produces ="application/json;charset=utf-8")
	public JSONObject monitoringPrint(@RequestParam(required=false) MultipartFile file) {
    
    		
		//POST请求访问
		JSONObject json = new JSONObject();		
		String s=PrintController.doPostWithJson("http://127.0.0.1:20173/v2.0/print/0015CA7350020300", file);	
		if(s!=null&&!"".equals(s)) {
    
    
			json.put("data", "访问成功");
		}else{
    
    
			json.put("data", "访问失败");
		}	
		return json;
	}
	/**
	 * 发送Post请求 调用这个方法 带json参数
	 * @param url	要请求的地址
	 * @param json	要发送的json格式数据
	 * @return 返回的数据
	 */
	public static String doPostWithJson(String url,MultipartFile Mfile){
    
    
		String returnValue = null;
        CloseableHttpClient httpclient = null;
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        try {
    
    
            //创建httpclient对象
        	httpclient = HttpClients.createDefault();
            //创建http POST请求
            HttpPost httpPost = new HttpPost(url);
            //文本参数用StringEntity,文件参数用MultipartEntityBuilder
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            //MultipartFile转File
            File file=multipartFileToFile(Mfile);
            
            builder.addBinaryBody("file", file);
        	httpPost.setHeader("File-Type","pdf");//请求头
        	HttpEntity reqEntity = builder.build();
        	httpPost.setEntity(reqEntity);
        	//发送请求,获取返回值
        	returnValue = httpclient.execute(httpPost,responseHandler);
		}catch (Exception e) {
    
    
			logger.error("发送post请求失败!"+e.getMessage());
		}finally {
    
    
			try {
    
    
				httpclient.close();
			} catch (IOException e) {
    
    
				logger.error("httpclient关闭失败!"+e.getMessage());
			}
		}
        return returnValue;
	}
	 /**
     * MultipartFile 转 File
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {
    
    
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
    
    
            file = null;
        } else {
    
    
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }
    /**
     * 获取流文件
     * @param ins
     * @param file
     */
    private static void inputStreamToFile(InputStream ins, File file) {
    
    
        try {
    
    
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
    
    
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
}

どなたでもお読みいただけます。知識が限られており、ブログの間違いや脱落は避けられません。アドバイスをいただければ幸いです。ありがとうございます。

おすすめ

転載: blog.csdn.net/qq_41936224/article/details/108281383