详解Java发送HTTP请求

 更新时间:2019年03月29日 16:27:49   作者:胖虎。。  
这篇文章主要介绍了Java发送HTTP请求,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

前言

请求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请求详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

相关文章

  • 一不小心就让Java开发踩坑的fail-fast是个什么鬼?(推荐)

    一不小心就让Java开发踩坑的fail-fast是个什么鬼?(推荐)

    这篇文章主要介绍了Java fail-fast,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-04-04
  • JDBC程序更新数据库中记录的方法

    JDBC程序更新数据库中记录的方法

    这篇文章主要介绍了JDBC程序更新数据库中记录的方法,涉及Java基于JDBC操作数据库的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-10-10
  • Java源码解析ThreadLocal及使用场景

    Java源码解析ThreadLocal及使用场景

    今天小编就为大家分享一篇关于Java源码解析ThreadLocal及使用场景,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-01-01
  • Java中的cglib代理详解

    Java中的cglib代理详解

    这篇文章主要介绍了Java中的cglib代理详解, 代理模式是一种设计模式,它可以为其他对象提供一种代理,以控制对该对象的访问,可以在运行时动态地创建代理对象,而不需要手动编写代理类的代码,需要的朋友可以参考下
    2023-09-09
  • 自己手写Mybatis通用batchInsert问题

    自己手写Mybatis通用batchInsert问题

    这篇文章主要介绍了自己手写Mybatis通用batchInsert问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • Java方法反射实现原理详解

    Java方法反射实现原理详解

    这篇文章主要为大家详细介绍了Java方法反射的实现原理,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-10-10
  • JDK19新特性使用实例详解

    JDK19新特性使用实例详解

    这篇文章主要为大家介绍了JDK19新特性使用实例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-09-09
  • SpringBoot项目打成War布署在Tomcat的详细步骤

    SpringBoot项目打成War布署在Tomcat的详细步骤

    这篇文章主要介绍了SpringBoot项目打成War布署在Tomcat,本文分步骤结合图文实例给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-03-03
  • IntelliJ IDEA中新建Java class的解决方案

    IntelliJ IDEA中新建Java class的解决方案

    今天小编就为大家分享一篇关于IntelliJ IDEA中新建Java class的解决方案,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2018-10-10
  • java教程之java继承示例详解

    java教程之java继承示例详解

    这篇文章主要介绍了java继承示例详解,需要的朋友可以参考下
    2014-04-04

最新评论