Call Interface no1.

1.首先是URL :

一班形式为:URL restURL=new URL(url);
其中 url表示 目标访问地址. restURL表示 返回结果
URL类是java.net.*下的类

2.再次是请求方式:
一般形式为:setRequestMethod("POST");
其中 有两种请求方式一个是GET,一个是POST.

3.是否输出 或者读入:
一般形式为:setDoOutput(true);setDoInput(true);
setDoInput() : // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认是false;
setDoOutput(): // 设置是否从httpUrlConnection读入,默认情况下是true;

4.用户交互(例如弹出一个验证对话框)的上下文中对此 URL 进行检查:
一般形式为:setAllowUserInteraction();
allowUserInteraction如果为 true,则在允许用户交互(例如弹出一个验证对话框)的上下文中对此 URL 进行检查.

5.属性=值&属性=值 这种形式传递的,传递给服务器,让服务器自己去处理:
一般形式为:query
例如:username=angusbao&password=123456
//拼接字符串map形式

6.创建完成后返回流:
一般形式:close();

7.生成时间戳:Date

 public static String getCurrentTime() {
        Date NowDate = new Date();
       SimpleDateFormat formatter =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         CurrentTime = formatter.format(NowDate);
      return CurrentTime;
   }
//拼接参数=xx&参数=xx
    public static String createLiinkStringByGet(Map<String, String> params) throws UnsupportedEncodingException {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            value = URLEncoder.encode(value, "UTF-8");
            if (i == keys.size() - 1) {
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }
        return prestr;

    }
    @Test
    public void testdeno() throws UnsupportedEncodingException {
        Map<String,String> map=new HashMap<String,String>();
        map.put("1","hello");
        map.put("2","world");
        System.out.println(createLiinkStringByGet(map));
        //打印结果:1=hello&2=world

    }

第一种调用方式:

   public String load(String url,String query) throws IOException {

        //设置连接url
        URL restURL=new URL(url);
        /*
        此处的urlConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类 的子类HttpURLConnection
         */
        HttpURLConnection conn=(HttpURLConnection) restURL.openConnection();
        /*
            请求方式
         */
        conn.setRequestMethod("POST");
        ////设置是否从httpUrlConnection读入,默认情况下是true; httpUrlConnection.setDoInput(true);
        conn.setDoOutput(true);
         //allowUserInteraction 如果为 true,则在允许用户交互(例如弹出一个验证对话框)的上下文中对此 URL 进行检查。
        conn.setAllowUserInteraction(false);
        PrintStream ps=new PrintStream(conn.getOutputStream());
        ps.close();
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line,resultStr="";
        while(null!=(line=bufferedReader.readLine())){
            resultStr+=line;
        }
        System.out.println("241235"+resultStr);
        bufferedReader.close();
        return resultStr;
    }
    @Test
    public void demoR() throws IOException {

        String resultString=load("http://192.168.10.89:8080/eoffice-restful/resources/sys/oaholiday",
                "floor=first&year=2017&month=9&isLeader=N");

    }

第二种调用方式:

1.首先还是url
格式:URL url=new URL(path);

2.设置通用的请求属性:
格式:

conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

3.设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内.
格式:

conn.setDoOutput(true);
conn.setDoInput(true);

4.断开连接最好写上disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
格式:

conn.disconnect();

代码:

 public void interfaceUtils(String path,String data){
        try {
            URL url=new URL(path);
            HttpURLConnection conn= (HttpURLConnection) url.openConnection();
            PrintWriter out=null;
            //请求方式
            conn.setRequestMethod("POST");
            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            //设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
            //最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
            //post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            //发送请求参数即数据
            out.print(data);
            //缓冲数据
            out.flush();
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null) {
                System.out.println(str);
            }
            //关闭流
            is.close();
            //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            //固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
            conn.disconnect();
            System.out.println("完整结束");

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Test
    public void interfacedemo(){
        interfaceUtils("http://api.map.baidu.com/telematics/v3/weather?location=嘉兴&output=json&ak=5slgyqGDENN7Sy7pw29IUvrZ", "");
    }
发布了76 篇原创文章 · 获赞 9 · 访问量 6768

猜你喜欢

转载自blog.csdn.net/qq_37870369/article/details/97128645
今日推荐