zoukankan      html  css  js  c++  java
  • Java主流的Http请求--原生的HttpURLConnection

    import com.alibaba.fastjson.JSONObject;
    
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.text.ParseException;
    
    public class get_post {
    
        /**
         * Created by chengxia on 2018/12/4.
         */
            public String doPost(String URL){
                OutputStreamWriter out = null;
                BufferedReader in = null;
                StringBuilder result = new StringBuilder();
                HttpURLConnection conn = null;
                try{
                    URL url = new URL(URL);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    //发送POST请求必须设置为true
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    //设置连接超时时间和读取超时时间
                    conn.setConnectTimeout(30000);
                    conn.setReadTimeout(10000);
                    conn.setRequestProperty("Content-Type", "application/json");
                    conn.setRequestProperty("Accept", "application/json");
                    //获取输出流
                    out = new OutputStreamWriter(conn.getOutputStream());
                    //向post请求发送json数据
                    String jsonStr = "{"touser":"", "msgtype":"text",  "text":{" +
                            " "content":""}}";
                    out.write(jsonStr);
                    out.flush();
                    out.close();
                    //取得输入流,并使用Reader读取
                    if (200 == conn.getResponseCode()){
                        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                        String line;
                        while ((line = in.readLine()) != null){
                            result.append(line);
                            System.out.println(line);
                        }
                    }else{
                        System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    try{
                        if(out != null){
                            out.close();
                        }
                        if(in != null){
                            in.close();
                        }
                    }catch (IOException ioe){
                        ioe.printStackTrace();
                    }
                }
                return result.toString();
            }
    
            public String doGet(String URL){
                HttpURLConnection conn = null;
                InputStream is = null;
                BufferedReader br = null;
                StringBuilder result = new StringBuilder();
                try{
                    //创建远程url连接对象
                    URL url = new URL(URL);
                    //通过远程url连接对象打开一个连接,强转成HTTPURLConnection类
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    //设置连接超时时间和读取超时时间
                    conn.setConnectTimeout(15000);
                    conn.setReadTimeout(60000);
                    conn.setRequestProperty("Accept", "application/json");
                    //发送请求
                    conn.connect();
                    //通过conn取得输入流,并使用Reader读取
                    if (200 == conn.getResponseCode()){
                        is = conn.getInputStream();
                        br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                        String line;
                        while ((line = br.readLine()) != null){
                            result.append(line);
    //                        System.out.println(line);
                        }
                        //json类型字符串转为jsonObject
    //                    System.out.println(result);
                        JSONObject jsonObject = JSONObject.parseObject(String.valueOf(result));
                        //根据key值获取数据value
                        System.out.println(jsonObject.getString("access_token"));  //输出value1
                        Writer writer = null;
                        StringBuilder outputString = new StringBuilder();
                        try {
                            outputString.append(jsonObject.getString("access_token") + "
    ");
                            writer = new FileWriter("test.txt"); // true表示追加
                            writer.write(outputString.toString());
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                writer.close();
                            } catch (IOException e2) {
                                e2.printStackTrace();
                            }
                        }
    
    
    
                    }else{
                        System.out.println("ResponseCode is an error code:" + conn.getResponseCode());
                    }
                }catch (MalformedURLException e){
                    e.printStackTrace();
                }catch (IOException e){
                    e.printStackTrace();
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    try{
                        if(br != null){
                            br.close();
                        }
                        if(is != null){
                            is.close();
                        }
                    }catch (IOException ioe){
                        ioe.printStackTrace();
                    }
                    conn.disconnect();
                }
                return result.toString();
            }
    
    
        /** 读取文件数据,存入集合中
         * @return*/
        public static String readtFile(File file) throws IOException, ParseException {
            InputStreamReader read = null;// 考虑到编码格式
            try {
                read = new InputStreamReader(new FileInputStream(file), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            BufferedReader bufferedReader = new BufferedReader(read);
            String lineTxt = null;
            StringBuffer buffer = new StringBuffer();
            String line = " ";
            while ((line = bufferedReader.readLine()) != null) {
    //            System.out.println(lineTxt);
                buffer.append(line);
            }
    
            read.close();
            return buffer.toString();
        }
    
    
       public static void main(String[] args) throws Exception {
                 get_post http = new get_post();
    
    //            System.out.println("Testing 1 - Do Http GET request");
           //获取token的get方法
    //            http.doGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=&secret=");
    
                System.out.println("
    Testing 2 - Do Http POST request");
                File file = new File("test.txt");
                String token = readtFile(file);
                System.out.println(token);
                http.doPost("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+token);
    
            }
    
        }
  • 相关阅读:
    7.4 List集合
    vue学习笔记
    javaWEB中web.xml配置文件相关
    maven常用dos命令
    Oracle,sqlserver,mySQl的区别和联系:
    oracle数据库视图,序列,索引的sql语句查看
    java 异常处理
    线程专题
    package、folder和source folder的区别
    Java内存分配之堆、栈和常量池
  • 原文地址:https://www.cnblogs.com/wencong/p/15408269.html
Copyright © 2011-2022 走看看