zoukankan      html  css  js  c++  java
  • 【原生态】Http请求数据 与 发送数据

    今天项目组小弟居然问我怎么用java访问特定的地址获取数据和发送请求

    Http请求都是通过输入输出流来进行操作的,首先要制定GET或者POST,默认是GET,在安全和数据量较大情况下请使用post

    根据url建立链接,读取输入输出流,从中取得相应的返回数据,

    http是无序的,在安全性极高的地方请使用https,但是https传输效率差不多只是http的1/10,所以除非特别必要,请谨慎选择

    我将我以前写的微信开发代码贴一部分出来,这里就有根据地址获取请求数据和向某一个特定端口发送数据

    package com.xiao.weixin.service.impl;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.security.MessageDigest;
    import java.util.Arrays;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.annotation.Resource;
    
    import org.json.JSONObject;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Service;
    
    import com.xiao.weixin.common.jdbc.DataSource;
    import com.xiao.weixin.dao.WeixinApiMapper;
    import com.xiao.weixin.entity.AccessToken;
    import com.xiao.weixin.service.WeixinApiService;
    import com.xiao.weixin.utils.ApiUrl;
    import com.xiao.weixin.utils.CommonUtil;
    import com.xiao.weixin.utils.DateUtil;
    
    @Service(value = "weixinApiService")
    public class WeixinApiServiceImpl implements WeixinApiService {
    
        private Logger log = LoggerFactory.getLogger(WeixinApiServiceImpl.class);
    
        @Value("${weixin.appID}")
        private String appID;
    
        @Value("${weixin.appsecret}")
        private String appsecret;
    
        @Value("${weixin.menu}")
        private String menuString;
    
        @Value("${weixin.token}")
        private String weixinToken;
    
        @Resource
        private WeixinApiMapper weixinApiMapper;
    
        @Override
        @DataSource
        public String getAccessToken() {
            String access_token = null;
            try {
                AccessToken token = weixinApiMapper.findToken();// 数据库查找没过期的token并返回
                if (token != null) {
                    access_token = token.getAccessToken();
                }
            } catch (Exception e) {
                log.error("获取accessToken出错");
                e.printStackTrace();
            }
            log.debug("获取到的accessToken是:" + access_token);
            return access_token;
        }
    
        @Override
        public void refreshAccessToken() {
            log.debug("重新生成accessToken开始");
            try {
                String url = ApiUrl.GET_ACCESSTOKEN.replace("APPID", appID)
                        .replace("APPSECRET", appsecret);
                log.debug("重新获取token的请求地址为:" + url);
                URL urlGet = new URL(url);
                HttpURLConnection http = (HttpURLConnection) urlGet
                        .openConnection();
    
                http.setRequestMethod("GET");
                http.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
                http.setDoOutput(true);
                http.setDoInput(true);
                System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
                System.setProperty("sun.net.client.defaultReadTimeout", "30000");
    
                http.connect();
    
                InputStream is = http.getInputStream();
                int size = is.available();
                byte[] jsonBytes = new byte[size];
                is.read(jsonBytes);
                String message = new String(jsonBytes, "UTF-8");
                System.out.println("message:" + message);
                JSONObject json = new JSONObject(message);
                String access_token = json.getString("access_token");
                Integer expiresIn = json.getInt("expires_in");
                log.debug("重新生成accessToken结束   成功");
    
                // 根据取得的accessToken 来获取jsapi_ticket
                String ticketUrl = ApiUrl.GET_JSAPITICKET.replace("ACCESSTOKEN",
                        access_token);
                log.debug("重新获取jsapi_ticket的请求地址为:" + ticketUrl);
                URL ticketUrlGet = new URL(ticketUrl);
                HttpURLConnection tickeHttp = (HttpURLConnection) ticketUrlGet
                        .openConnection();
    
                tickeHttp.setRequestMethod("GET");
                tickeHttp.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
                tickeHttp.setDoOutput(true);
                tickeHttp.setDoInput(true);
                System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
                System.setProperty("sun.net.client.defaultReadTimeout", "30000");
    
                tickeHttp.connect();
    
                InputStream tickeIs = tickeHttp.getInputStream();
                byte[] tickeJsonBytes = new byte[tickeIs.available()];
                tickeIs.read(tickeJsonBytes);
                String tickeMessage = new String(tickeJsonBytes, "UTF-8");
                System.out.println("message:" + message);
                JSONObject ticketJson = new JSONObject(tickeMessage);
                String ticket = ticketJson.getString("ticket");
    
                AccessToken accessToken = new AccessToken();
                accessToken.setAppId(appID);
                accessToken.setSecret(appsecret);
                accessToken.setAccessToken(access_token);
                accessToken.setJsApiTicket(ticket);
                accessToken.setExpireTime(DateUtil.getExpiresTime(expiresIn));
                accessToken.setCreateTime(new Date());
                weixinApiMapper.insertToken(accessToken);// 将新生成的token保存到数据库
            } catch (Exception e) {
                log.error("获取accessToken出错");
                e.printStackTrace();
            }
        }
    
        @Override
        public String createMenu() {
            String access_token = getAccessToken();
            String url = ApiUrl.CREATE_MENU.replace("ACCESSTOKEN", access_token);
            log.debug("创建菜单的请求地址为:" + url);
            try {
                log.debug("menuString:" + menuString);
                URL urlPost = new URL(url);
                HttpURLConnection http = (HttpURLConnection) urlPost
                        .openConnection();
                http.setRequestMethod("POST");
                http.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded");
                http.setDoOutput(true);
                http.setDoInput(true);
                System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
                System.setProperty("sun.net.client.defaultReadTimeout", "30000");
    
                http.connect();
                OutputStream os = http.getOutputStream();
                os.write(menuString.getBytes("UTF-8"));
                os.flush();
                os.close();
    
                InputStream is = http.getInputStream();
                int size = is.available();
                byte[] jsonBytes = new byte[size];
                is.read(jsonBytes);
                String message = new String(jsonBytes, "UTF-8");
                return message;
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return "-1";
            } catch (IOException e) {
                e.printStackTrace();
                return "-1";
            }
        }
    
        @Override
        public Map<String, String> getSignature(String url) {
            Map<String, String> map = new HashMap<String, String>();
            try {
                String jsapi_ticket = getJsApiTicket();
                String nonceStr = "Wm3WZYTPz0wzccnW";
                long timestamp = System.currentTimeMillis() / 1000;
    
                map.put("appId", appID);
                map.put("timestamp", timestamp + "");
                map.put("nonceStr", nonceStr);
    
                String[] paramArr = new String[] { "jsapi_ticket=" + jsapi_ticket,
                        "timestamp=" + timestamp, "noncestr=" + nonceStr,
                        "url=" + url };
                Arrays.sort(paramArr);
                String content = paramArr[0].concat("&" + paramArr[1])
                        .concat("&" + paramArr[2]).concat("&" + paramArr[3]);
                log.debug("拼接之后的content为:" + content);
                MessageDigest md = MessageDigest.getInstance("SHA-1");
                byte[] digest = md.digest(content.toString().getBytes());
                String gensignature = CommonUtil.byteToStr(digest);
                map.put("signature", gensignature);
                return map;
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获取JSAPI签名信息失败,错误信息:" + e);
                return null;
            }
        }
    
        @Override
        public String getJsApiTicket() {
            String jsApiTicket = null;
            try {
                AccessToken token = weixinApiMapper.findToken();// 数据库查找没过期的token并返回
                if (token != null) {
                    jsApiTicket = token.getJsApiTicket();
                }
            } catch (Exception e) {
                log.error("获取jsApiTicket出错");
                e.printStackTrace();
            }
            log.debug("获取到的jsApiTicket是:" + jsApiTicket);
            return jsApiTicket;
        }
    
    }
  • 相关阅读:
    mysql总结
    spirngmvc整合mybatis实现CRUD
    java lesson09总结
    Java lesson08 Homework
    java Lesson08总结
    【DFS】bzoj2435 [Noi2011]道路修建
    【BFS】bzoj2252 [2010Beijing wc]矩阵距离
    【BFS】bzoj1054 [HAOI2008]移动玩具
    【搜索】bzoj3109 [cqoi2013]新数独
    【搜索】【约数个数定理】[HAOI2007]反素数ant
  • 原文地址:https://www.cnblogs.com/xiaochangwei/p/5045264.html
Copyright © 2011-2022 走看看