springboot+http请求转换

springboot+http请求转换

##此文章记录一下项目需要小程序和pc相互调用相同业务逻辑的接口,此方法需要请求报文中添加目标url,无其它多余代码开发

http请求

后面再专门学习http
1.方法+url+协议/版本
2.请求头
3.主题
springboot+http请求转换_第1张图片

springboot

Pom.xml文件
<parent>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-parent</artifactId>
   <version>2.1.0.RELEASE</version>
</parent>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
 <dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>fastjson</artifactId>
     <version>1.2.44</version>
  </dependency>

@SpringBootApplication
public class Application {
     
    public static void main(String[] args) {
     
        SpringApplication.run(Application.class,args);
    }
}
Controller---
@RequestMapping("/adapter")
    @ApiOperation(value = "", notes = "返回成败信息")
    public RestMessage adapter(@RequestBody String requestParameter) {
     
        //此Controller调用开始时间(行为日志)
        Date startDate = new Date();
        String sdfsd=AESUtilTools.encrypt(requestParameter);
        String requestJsonEnc = AESUtilTools.decrypt(sdfsd);//解密
        JSONObject  requestJson = JSONObject.parseObject(requestJsonEnc);
        RestMessage restMessage = addattendanceruleServiceImpl.Adapter(requestJsonEnc);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return restMessage;
    }


public static String httpSend(String requestUrl,String requestXML ) throws Exception {
     
        String msgXML = "";
        HttpURLConnection httpConnection = null;
        try {
     
            URL url = new URL(requestUrl);
            httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setRequestMethod("POST");
            httpConnection.setConnectTimeout(500);
            httpConnection.setDoOutput(true);
            httpConnection.setDoInput(true);
            httpConnection.setAllowUserInteraction(true);
            httpConnection.setRequestProperty("Content-type","application/json");
           
            httpConnection.setRequestProperty("accept", "*/*");
            httpConnection.setRequestProperty("connection", "Keep-Alive");
            httpConnection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0;Windows NT 5.1;SV1)");
            String user = SysConst.getProperty("User");
            String passwordkey =SysConst.getProperty("password");
            BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
    		// 密钥,密钥从配置文件中获取
    		textEncryptor.setPassword("password");
    		// 解密,密文从配置文件中获取
    		String pwd = textEncryptor.decrypt(passwordkey);
            String auth = user+":"+pwd;
            byte[] rel = Base64.encodeBase64(auth.getBytes());
            String res = new String(rel);
  //添加加密信息 
           httpConnection.setRequestProperty("Authorization","Basic " + res);
//            httpConnection.setReadTimeout(readTimeout);
            httpConnection.connect();
            OutputStream outputStream = httpConnection.getOutputStream();
            outputStream.write(requestXML.getBytes("utf-8"));
            outputStream.flush();
            outputStream.close();
            // 3、返回数据
            InputStreamReader inputStreamReader = new InputStreamReader(
                    httpConnection.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);

            String inputLine = "";
            StringBuffer inputLines = new StringBuffer();
            inputLine = bufferedReader.readLine();
            while (inputLine != null) {
     
                inputLines.append(inputLine);
                inputLine = bufferedReader.readLine();
            }
            inputStreamReader.close();
            bufferedReader.close();
            // 4、关闭连接
            httpConnection.disconnect();
            msgXML = inputLines.toString();
            return msgXML;
        } catch (Exception e) {
     
            e.printStackTrace();
            throw e;
        } finally {
     
            if (httpConnection != null) {
     
                httpConnection.disconnect();
            }
        }
    }

方式二

public static String callByHttpPost(String url , String json) throws ExecutionException{
     
		HttpClient httpClient = new HttpClient();
		PostMethod postMethod = new PostMethod(url);
		String responseData = "";
		try {
     
			postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
			postMethod.setRequestHeader("Content-Type","application/json");
			StringRequestEntity requestEntity = new StringRequestEntity(json, "application/json", "UTF-8");
			postMethod.setRequestEntity(requestEntity);
			int statusCode = httpClient.executeMethod(postMethod);
			if (statusCode == HttpStatus.SC_OK) {
     
				responseData =  postMethod.getResponseBodyAsString();
			}
		} catch (Exception e) {
     
			Logger logger = Logger.getLogger(e.toString());
			throw new ExecutionException(e);
		}finally{
     
			postMethod.releaseConnection();
		}
		return responseData;
	}

你可能感兴趣的:(springboot,java,http,spring)