详解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
投稿
猜你喜欢
- 需要设置允许不安全代码.....项目->属性->生成->允许不安全代码/// <summary> &
- 前言5个xml文件实现 按钮的圆角、阴影效果以及按下变化效果实现drawable/shape.xml<?xml version=&qu
- Java8对于LocalDateTime的序列化和反序列化这里以jackjson为例配置反序列化工具/** * 时间戳反序列化时间 * *
- summarydetail传统的Spring项目会有很多的配置文件,比如我们要使用Redis,一般除了对应的依赖的jar包我们还需要在app
- 本文主要介绍了c# 使用线程对串口serialPort进行收发数据,分享给大家,具体如下:一共写了四种方法,窗体界面都是一样的:方法一:us
- 会话技术会话:一次会话中包含多次请求和响应。一次会话:浏览器第一次给服务器资源发送请求,会话建立,直到有一方断开为止功能:在一次会话的范围内
- 首先引入pom <!--SpringBoot 2.1.0--> <parent>  
- 代码如下所示:using System;using System.Collections.Generic;using System.Linq
- 如何实现封装可以分为两步:第一步:将类的变量声明为private。第二步:提供公共set和get方法来修改和获取变量的值。代码展示publi
- 限时抢购倒计时实现效果图布局:<LinearLayout android:id="@+id/ll_
- Java 开发语言中实现HTTP请求的方法主要有两种:一种是JAVA的标准类HttpUrlConnection,比较原生的实现方法;另一种是
- 不同的浏览器会把cookie文件保存在不同的地方以下是C# WebBrowser控件cookies的存放路径C:\Users\{你的帐号名}
- java可以通过Runtime.getRuntime().exec()执行一个操作系统的命令,在操作系统层面执行命令也就创建了一个进程,Ja
- 概述从今天开始, 小白我将带大家开启 Jave 数据结构 & 算法的新篇章.循环队列循环队列 (Circular Queue) 是一
- 一.以springboot为例,建立代码1.IExecCommandServer:public interface IExecCommand
- 先看下面的这组字符,如果输出来,它是无法靠右对齐: Source Codestring[] s1 = { "300",
- /* * 使用 C# 动态编译代码和执行 * 作者: yaob */ static void Main(string[] args) { /
- package cn.liangjintang.httpproxy;import java.io.BufferedReader;import
- retrofit post请求上传表单和文件最重要的就是就是去构建RequestBody,今天为大家带来一种超级简单的上传方式Body方式:
- 在刚接触后台线程的时候,觉得线程神秘且高深,并且时常有先辈们千叮万嘱:能不用的时候,尽量不要用,千万不要滥用线程,否则会发生预料不到的结果。