java的http请求实例

摘要:
软件包vqmp.data.pull.vqmpull.common.utils;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.http.HttpEntity;importorg.springframework.http.HttpHeaders;进口弹簧
java的http请求实例第1张java的http请求实例第2张
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();

    }

}
View Code
java的http请求实例第3张java的http请求实例第4张
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;
    }
}
View Code

免责声明:文章转载自《java的http请求实例》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇PAT 甲级 1147 Heaps (30 分)lombok日志包的使用下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

springsession生成sessionid不一致问题解决

不废话,本人遇到的问题主要是两个不同的springboot版本,需要共享sessionid。 1.配置application #cookie作用域server.servlet.session.cookie.path=/server.servlet.session.cookie.max-age=-1server.servlet.session.cookie....

在Delphi中高效执行JS代码

因为一些原因,需要进行encodeURIComponent和decodeURIComponent编码,在Delphi中找了一个,首先是发现不能正确编码+号,后面强制处理替换了,勉强可用。 后面发现多次使用后delphi自带的HttpEncode会报Out of Memory. 以上可能是我使用的不好,但没有找到解决办法。 后面想到直接采用运行JavaScr...

Windows IIS Web services性能计数器说明

IIS Global Active Flushed Entries Active Flushed Entries 是缓存文件句柄,当前传输全部完成后将关闭此句柄。IIS Global 对象。 Web Anonymous Users/Sec 用户通过 Web 服务进行的匿名连接数。 IIS Global BLOB Cache Flushes 自服务器启动后的...

FTP文件上传下载(C#)

下面是ftp上传下载工具,不能直接运行,请删除不必要的代码。 /// <summary> /// ftp文件上传下载 /// </summary> public class FtpHelper { private string FtpServer; private st...

java property 配置文件管理工具框架,避免写入 property 乱序

property property 是 java 实现的 property 框架。 特点 优雅地进行属性文件的读取和更新 写入属性文件后属性不乱序 灵活定义编码信息 使用 OO 的方式操作 property 文件 支持多级对象引用 变更日志 ChangeLog 快速开始 环境依赖 Maven 3.x Jdk 1.7+ Maven 引入依赖 <de...

Base64加密解密

Base64加密解密using System; using System.Collections.Generic; using System.Text; namespace Dachie { class Program { static void Main(string[] args) {...