900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > 使用HttpClient模拟HTTP发送POST或GET请求

使用HttpClient模拟HTTP发送POST或GET请求

时间:2024-01-01 11:13:24

相关推荐

使用HttpClient模拟HTTP发送POST或GET请求

在Java开发中,服务与服务之间进行调用,需要使用HttpClient发送HTTP请求,以下是使用Java实现模拟HTTP发送POST或GET请求的代码

1、pom.xml中导入HTTP依赖

<!-- 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);//判断返回状态是否为200if(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,文件参数用MultipartEntityBuilderStringEntity 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("");//POST请求访问JSONObject json = new JSONObject();json.put("data", "成功");//参数HttpClientUtil.doPostWithJson("", 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:3/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,文件参数用MultipartEntityBuilderMultipartEntityBuilder builder = MultipartEntityBuilder.create();//MultipartFile转FileFile 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();}}}

4、x-www-form-urlencoded类型的参数

实现代码

public class Test {public static void main(String[] args) {List<NameValuePair> params = new ArrayList<NameValuePair>();NameValuePair pair = new BasicNameValuePair("grant_type", "client_credentials");NameValuePair pair2 = new BasicNameValuePair("app_key", "YLbbATeusEJbPCZiZ1n6paICffMu");NameValuePair pair3 = new BasicNameValuePair("app_secret", "oR93ABEWRDAIldXpZ6W4EbOvmV8NfKiMPl3OcO8U41yjeXNGaNNgr1xC4DGe5");params.add(pair);params.add(pair2);params.add(pair3);String postForString = postWithParamsForString("/token", params);System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>post:"+postForString);}}//POST请求public static String postWithParamsForString(String url, List<NameValuePair> params){HttpClient client = HttpClients.createDefault();HttpPost httpPost = new HttpPost(url);String s = "";try {httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");HttpResponse response = client.execute(httpPost);int statusCode = response.getStatusLine().getStatusCode();if(statusCode==200){HttpEntity entity = response.getEntity();s = EntityUtils.toString(entity);}} catch (IOException e) {e.printStackTrace();}return s;}

欢迎大家阅读,本人见识有限,写的博客难免有错误或者疏忽的地方,还望各位大佬指点,在此表示感谢。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。