详解Java发送HTTP请求
作者:胖虎。。 发布时间:2022-01-09 14:53:57
标签:Java,HTTP,get,post
前言
请求http的Demo是个人亲测过,目前该方式已经在线上运行着。因为是http请求,所有发送post 和get 请求的demo都有在下方贴出,包括怎么测试,大家可直接 copy到自己的项目中使用。
正文
使用须知
为了避免大家引错包我把依赖和涉及到包路径给大家
import java.net.HttpURLConnection;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.8</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
HTTP 发送 get 请求
首先我们引入两个包
发送get请求的工具类,可直接 copy 使用即可
另外,我抛出异常的代码大家改成自己业务的异常,不需要就删除掉。
参数说明:
host:ip
servUri:url
reString:参数
public static String getHttpData(String host, String servUri, String reString) throws Exception {
StringBuffer sb = new StringBuffer();
sb.append("getHttpData:host:" + host + ",servUri:" + servUri + ",reString:" + reString);
String strResp = null;
try {
URI uri = new URIBuilder().setScheme("http").setHost(host).setPath(servUri)
.setParameter("strInfo", reString).build();
HttpGet httpGet = new HttpGet(uri);
CloseableHttpClient client3 = HttpClients.createDefault();
HttpResponse resp;
resp = client3.execute(httpGet);
if (resp.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
strResp = EntityUtils.toString(resp.getEntity());
logger.info("the return result:{}", strResp);
} else {
logger.info("Error Response:", resp.getStatusLine().toString());
throw new CommonBusinessException(CommonConstants.TASK_RELEASE_WCF,
CommonConstants.TASK_RELEASE_WCF_DESC);
}
} catch (Exception e) {
logger.error(sb.toString() + ":" + e.getMessage(), e.getCause());
throw new CommonBusinessException(CommonConstants.TASK_RELEASE_WCF, CommonConstants.TASK_RELEASE_WCF_DESC);
}
return strResp;
}
HTTP 发送 post 请求
发送post分两种,我分两种的原因是为了让大家方便,想传对象和 json 可以直接复制过用就可以用,不用你们在转了。
第一种是直接接收json
参数明说:
url:url
json:参数
public static String doPostData(String url, String json) throws Exception {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
String result = "";
HttpResponse res = null;
try {
StringEntity s = new StringEntity(json.toString(), "UTF-8");
s.setContentType("application/json");
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json; charset=utf-8");
post.setEntity(s);
res = client.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(res.getEntity());
return HttpStatus.SC_OK + "";
}
} catch (Exception e) {
if(res == null) {
return "HttpResponse 为 null!";
}
throw new RuntimeException(e);
}
if(res == null || res.getStatusLine() == null) {
return "无响应";
}
return res.getStatusLine().getStatusCode() + "";
}
@Test
public void test12() throws Exception {
String HOST = "http://eipwcf.aspirecn.com/SvcEF/Service1.svc/WCF_EF_MSA_GetDataInfo_P";
HttpClient client = new HttpClient();
JSONObject json = new JSONObject();
json.put("msgId", msgId);
String reslut=client.doPostData(HOST, json);
}
第二种是参数是对象
参数说明:
url:url
tram:对象
public static String doHttpPostData(String url, TaskReleaseApprovalModel tram)
throws Exception {
StringBuffer sb = new StringBuffer();
sb.append("doHttpPostData:url:" + url + ",tram:" + tram.toString() + ",contentType:" + contentType);
logger.info(sb.toString());
String tmpString = "";
HttpPost request = new HttpPost(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
ObjectMapper mapper = new ObjectMapper();
String jsonString;
try {
jsonString = mapper.writeValueAsString(tram);
StringEntity entity = new StringEntity(jsonString, "UTF-8");
request.setEntity(entity);
CloseableHttpClient client = HttpClients.createDefault();
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
tmpString = EntityUtils.toString(response.getEntity());
logger.info("the post result:tmpString:{}", tmpString);
} else {
logger.info("the post failure:tmpString:", tmpString);
throw new CommonBusinessException(CommonConstants.TASK_RELEASE_WCF,
CommonConstants.TASK_RELEASE_WCF_DESC);
}
} catch (Exception e) {
logger.error(sb.toString() + ":" + e.getMessage(), e.getCause());
throw new CommonBusinessException(CommonConstants.TASK_RELEASE_POSTWCF,
CommonConstants.TASK_RELEASE_POSTWCF_DESC);
}
return tmpString;
}
这个方法我想不用写测试类大家也会用,传过去对象和地址就可以了,很方便很简单。
以上所述是小编给大家介绍的Java发送HTTP请求详解整合网站的支持!
来源:https://blog.csdn.net/weixin_38003389/article/details/88661280
0
投稿
猜你喜欢
- 前段时间分享了《阅读跟踪 Java 源码的几个小技巧》是基于 Eclipse 版本的,看大家的留言都是想要 IDEA 版本的源码阅读技巧。所
- 本文实例讲述了Java编程实现统计一个字符串中各个字符出现次数的方法。分享给大家供大家参考,具体如下:import java.util.It
- 一、目标效果聊天会话页的列表效果1、聊天数据不满一屏时,顶部显示所有聊天数据2、插入消息时如果最新消息紧靠列表底部时,则插入消息会使列表向上
- 做Java编程,难免会遇到多线程的开发,但是JDK8这个CompletableFuture类很多开发者目前还没听说过,但是这个类实在是太好用
- 经典的排序算法有八种,分别为:冒泡排序选择排序插入排序归并排序希尔排序快速排序堆排序基数排序其中冒泡排序、选择排序、插入排序称为三大基本排序
- 问题描述这里我想测试某个与springboot相关的问题,结果在搭建mybatis时,发现没有成功从数据库中获取数据,报错信息为com.my
- 本文实例为大家分享了Java NIO实现多人聊天室的具体代码,供大家参考,具体内容如下1. 服务器端代码ChatServer类:packag
- 本文实例讲述了C#禁止textbox复制、粘贴、剪切及鼠标右键的方法。分享给大家供大家参考。具体如下:class MyTextBox : S
- 在java 编程中,我们常常有这样的需求:需要将一段字符串内的特定字符串,按照一定规则查找出来或替换,比如匹配文本开头规则和结束规则。以下就
- 1.面向接口编程和面向对象编程是什么关系首先,面向接口编程和面向对象编程并不是平级的,它并不是比面向对象编程更先进的一种独立的编程思想,而是
- Lucene从今天开始,我们要开始介绍Lucene中索引构建的流程。因为索引构建的逻辑涉及到的东西非常多,如果从构建入口IndexWrite
- 进程同步用来实现程序并发执行时候的可再现性。一.进程同步及异步的概念1.进程同步:就是在发出一个功能调用时,在没有得到结果之前,该调用就不返
- 1.先下载微信分享的jar包放在lib目录下,并且添加依赖,清单文件添加<activity
- SlidingDrawer效果想必大家也见到过,它就是1.5模拟器上进入应用程序列表的效果。下面是截图一、简介 SlidingDr
- Struct的理论看过好一些,可是工作上基本没有应用过,Class倒处处都有。难道Struct就没有什么使用价值吗?搜了一下如何在类和结构中
- 这篇文章主要介绍了java加载property文件配置过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,
- 先谈一谈struts2实现文件的上传和下载实例实现的原理:Struts 2是通过Commons FileUpload文件上传。Commons
- MyBatis 是一款优秀的持久层框架,被各大互联网公司使用,本文使用Spring Boot整合Mybatis,并完成CRUD操作。为什么要
- 本文实例讲述了java实现单词搜索迷宫游戏。分享给大家供大家参考。具体分析如下:我们在杂志上,经常能够看到找单词的小游戏,在一个二维表格中,
- 在我们平时写程序的时候,有些参数是经常改变的,而这种改变不是我们预知的。比如说我们开发了一个操作数据库的模块,在开发的时候我们连接本地的数据