package vqmp.data.pull.vqmpull.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import vqmp.data.pull.vqmpull.common.enums.ResultEnum;
import vqmp.data.pull.vqmpull.common.exception.VQMPException; import java.util.List; /**
* @author 01372231
* @
* @date 2019/3/4 15:14
*/
public class RequestUtil {
private static final Logger logger = LoggerFactory.getLogger(RequestUtil.class); private RequestUtil() {
throw new IllegalAccessError("Instantiate me is forbid");
} /**
*
*
* @return 返回cookie值
* @throws Exception 获取token失败
*/
public static List<String> getItobToken(String itobTokenUrl) { LinkedMultiValueMap<String, String> body = new LinkedMultiValueMap();
body.add("userRole", "VIP");
body.add("centerName", "SF"); ResponseEntity request = requestEntity(itobTokenUrl, HttpMethod.POST, body, new HttpHeaders());
HttpHeaders headers = request.getHeaders();
List<String> strings = headers.get("Set-Cookie");
if (null == strings) {
logger.error("url{}-获取token失败", itobTokenUrl);
throw new VQMPException(ResultEnum.FAIL.getCode(), "获取token失败");
} //获取jira数据
return strings;
} public static ResponseEntity requestEntity(String url, HttpMethod method, MultiValueMap<String, String> body, HttpHeaders headers) {
logger.info("发送请求地址url:{}", url);
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(10000);
RestTemplate restTemplate = new RestTemplate(requestFactory);
if (method.equals(HttpMethod.POST)) {
headers.set("Content-Type", "application/x-www-form-urlencoded");
}
HttpEntity entity = null;
if (null != body) {
entity = new HttpEntity(body, headers);
} else {
entity = new HttpEntity(headers); }
ResponseEntity<String> responseEntity = restTemplate.exchange(url, method, entity, String.class);
if (responseEntity.getStatusCode() == HttpStatus.REQUEST_TIMEOUT) {
logger.error("接口请求超时,接口地址: {}", url);
throw new VQMPException("接口" + url + "请求超时");
} return responseEntity; } /**
* get response body
*
* @param url request url
* @param method reuqest method
* @param body request params
* @param headers request headers
* @return
* @throws Exception
*/
public static String request(String url, HttpMethod method, MultiValueMap<String, Object> body, HttpHeaders headers) {
logger.info("发送请求地址url:{}", url);
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(10000);
RestTemplate restTemplate = new RestTemplate(requestFactory);
headers.set("Content-Type", "application/x-www-form-urlencoded");
HttpEntity entity = new HttpEntity(body, headers); ResponseEntity<String> responseEntity = restTemplate.exchange(url, method, entity, String.class);
if (responseEntity.getStatusCode() == HttpStatus.REQUEST_TIMEOUT) {
logger.error("接口请求超时,接口地址: {}", url);
throw new VQMPException("接口" + url + "请求超时");
}
if (responseEntity.getStatusCode().value() != 200) {
throw new VQMPException(String.format("tcmp响应报错 : {} ", responseEntity.toString()));
} return responseEntity.getBody(); } }
package com.sf.tcmp.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL; /**
*
* @author 01368324
*
*/
public final class RequestAPIUtil { private static final Logger logger = LoggerFactory.getLogger(RequestAPIUtil.class); private static final String LOGSTRING = "接口地址:{},接口名:{}"; private RequestAPIUtil(){
throw new IllegalAccessError("Instantiate me is forbid");
} /**
* Jira 的webService接口请求
* @param urlStr 请求url
* @param apiName 接口名
* @param arg 参数
* @return
*/
public static String postRequest(String urlStr,String apiName,String arg){
String result = "";
try {
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setConnectTimeout(10000);
con.setRequestProperty("Content-Type", "application/xml;");
OutputStream oStream = con.getOutputStream();
String soap = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"+
"<soapenv:Envelope "+
"xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "+
"xmlns:gs=\"http://server.itms.inf.itdd.sf.com/\">"+
" <soapenv:Header/>"+
" <soapenv:Body>"; soap = soap+" <gs:"+apiName+">";
soap=soap+" <arg0>" + arg + "</arg0>"; soap = soap+" </gs:"+apiName+">";
soap = soap+" </soap:Body>"+
"</soapenv:Envelope>";
oStream.write(soap.getBytes());
oStream.close();
InputStream iStream = con.getInputStream();
Reader reader = new InputStreamReader(iStream,"utf-8"); int tempChar;
String str = new String("");
while((tempChar = reader.read()) != -1){
str += Character.toString ((char)tempChar);
}
//下面这行输出返回的xml到控制台,相关的解析操作大家自己动手喽。
//如果想要简单的话,也可以用正则表达式取结果出来。
result = str.substring(str.indexOf("<return>")+8, str.indexOf("</return>"));
iStream.close();
oStream.close();
con.disconnect();
} catch (ConnectException e){
logger.error(LOGSTRING,urlStr,apiName,e);
}catch (IOException e) {
logger.error(LOGSTRING,urlStr,apiName,e);
} catch (Exception e){
logger.error(LOGSTRING,urlStr,apiName,e);
}
return result;
}
/**
* webservice接口请求demo
* @return
*/
public static String requestDemo(){
String result = "";
try {
//http://10.202.6.70:6060/itdd-app/inf-ws/SyncITMSData
String urlStr = "";
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
OutputStream oStream = con.getOutputStream();
//下面这行代码是用字符串拼出要发送的xml,xml的内容是从测试软件里拷贝出来的
//需要注意的是,有些空格不要弄丢哦,要不然会报500错误的。
//参数什么的,你可以封装一下方法,自动生成对应的xml脚本
String soap = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"+
"<soapenv:Envelope "+
"xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "+
"xmlns:gs=\"http://server.itms.inf.itdd.sf.com/\">"+
" <soapenv:Header/>"+
" <soapenv:Body>"+
" <gs:getVersionBySysCode>"+
" <arg0>" + "ESG-SDEIS-CORE" + "</arg0>"+
" </gs:getVersionBySysCode>"+
" </soap:Body>"+
"</soapenv:Envelope>";
oStream.write(soap.getBytes());
oStream.close();
InputStream iStream = con.getInputStream();
Reader reader = new InputStreamReader(iStream); int tempChar;
StringBuilder str = new StringBuilder();
while((tempChar = reader.read()) != -1){
str.append(Character.toString((char) tempChar));
}
//下面这行输出返回的xml到控制台,相关的解析操作大家自己动手喽。
//如果想要简单的话,也可以用正则表达式取结果出来。
result = str.substring(str.indexOf("<return>")+8, str.indexOf("</return>"));
iStream.close();
oStream.close();
con.disconnect();
} catch (Exception e) {
logger.error("content:",e);
}
return result;
}
}

java的http请求实例的更多相关文章

  1. Flex通信-与Java实现Socket通信实例

    Flex通信-与Java实现Socket通信实例  转自:http://blessht.iteye.com/blog/1136888 博客分类: Flex 环境准备 [服务器端] JDK1.6,“ja ...

  2. java实现HTTP请求的三种方式

    目前JAVA实现HTTP请求的方法用的最多的有两种:一种是通过HTTPClient这种第三方的开源框架去实现.HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,Ht ...

  3. java HttpClient POST请求

    一个简单的HttpClient POST 请求实例 package com.httpclientget; import java.awt.List; import java.util.ArrayLis ...

  4. 【转载】java实现HTTP请求的三种方式

    目前JAVA实现HTTP请求的方法用的最多的有两种:一种是通过HTTPClient这种第三方的开源框架去实现.HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,Ht ...

  5. java实现HTTP请求 HttpUtil

    示例: package com.sensor.utils; import java.net.HttpURLConnection; import java.net.URL; public class H ...

  6. HTTP:Java实现HTTP请求的三种方式

    目前JAVA实现HTTP请求的方法用的最多的有两种: 一种是通过HTTPClient这种第三方的开源框架去实现.HTTPClient对HTTP的封装性比较不错,通过它基本上能够满足我们大部分的需求,H ...

  7. Java发送Http请求并获取状态码

    通过Java发送url请求,查看该url是否有效,这时我们可以通过获取状态码来判断. try { URL u = new URL("http://10.1.2.8:8080/fqz/page ...

  8. java 实现https请求

    java 实现https请求 JSSE是一个SSL和TLS的纯Java实现,通过JSSE可以很容易地编程实现对HTTPS站点的访问.但是,如果该站点的证书未经权威机构的验证,JSSE将拒绝信任该证书从 ...

  9. 第三篇 :微信公众平台开发实战Java版之请求消息,响应消息以及事件消息类的封装

    微信服务器和第三方服务器之间究竟是通过什么方式进行对话的? 下面,我们先看下图: 其实我们可以简单的理解: (1)首先,用户向微信服务器发送消息: (2)微信服务器接收到用户的消息处理之后,通过开发者 ...

随机推荐

  1. BMIP002协议介绍

    比原BMIP002协议 概述 比原链技术社区最近提出了一套资产规范提议,该提议允许在issue类型的交易中实现标准资产token.该标准定义资产在链上的基本功能,以及发行人通过智能合约管理资产的规范. ...

  2. CentOS7攻克日记(四) —— 安装Mysql和Redis

    这一篇主要安装mysql,redis等数据库   在这篇开始之前,有一个坑,上一篇更改python软连接的时候,尽量都用名字是python3来软连接/usr/../bin/python3.6,把名字是 ...

  3. LINQ to Entities does not recognize the method 'System.DateTime AddDays(Double)' method, and this method cannot be translated into a store expression.

    NormalSubmission=analysis.Count(x=>x.FinishTime<= endTime.AddDays(1))报错linq不能识别 => var endT ...

  4. C语言学习——bsmap-2.74_main.cpp

    素材路径:https://www.codeforge.cn/read/428275/bsmap-2.74-_-main.cpp__html 1.C/C++预处理指令,常见的预处理指令如下: #空指令, ...

  5. GeoJson

    几何对象.特征对象.特征对象集合.

  6. 在 Laravel 项目中使用 Elasticsearch 做引擎,scout 全文搜索(小白出品, 绝对白话)

    项目中需要搜索, 所以从零开始学习大家都在用的搜索神器 elasiticsearch. 刚开始 google 的时候, 搜到好多经验贴和视频(中文的, 英文的), 但是由于是第一次接触, 一点概念都没 ...

  7. cron表达式总结

    cron表达式用于配置cronTrigger的实例,在定时任务中会用到cron表达式.cron表达式实际上是由七个子表达式组成.这些表达式之间用空格分隔. 可通过工具校验:http://cron.qq ...

  8. setTimeout异步

    同步任务和异步任务 同步和异步操作的区别就是是否阻碍后续代码的执行. 同步任务是那些没有被引擎挂起.在主线程上排队执行的任务.只有前一个任务执行完毕,才能执行后一个任务. 异步任务是那些被引擎放在一边 ...

  9. 环境搭建之allure的安装配置,及简单使用

    环境准备 首先是要安装好jdk的电脑上,运行java.javac这些命令都没有问题,要不安装allure时会报错 下载allure 如果直接用Jenkins上的插件,并不需要下载安装 allure官网 ...

  10. js查找、自组织数据

    function search(arr, data) { ; i < arr.length; ++i) { if (arr[i] == data) { return true; } } retu ...