URL调用http接口

  • java在代码中调用接口
public static void main(String[] args) {
        try {
            //创建接口地址对象
            URL url = new URL("http://localhost:8888/menu");
            //根据url对象来生成一个打开连接http请求
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = null;
            while(null != (line = br.readLine())){
                System.out.println(line);
            }
            br.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  • URL类
- url类
URL表示统一资源定位符,指向万维网上的“资源”的指针。 资源可以像文件或目录一样简单,或者可以是对更复杂的对象的引用
一般来说,URL可以分为几个部分。 请考虑以下示例: 
http://www.example.com/docs/resource1.html
上面的URL表示要使用的协议是http (超文本传输协议),并且信息驻留在名为www.example.com的主机上。 该主机上的信息名为/docs/resource1.html 主机上此名称的确切含义取决于协议和主机。 信息通常驻留在一个文件中,但它可以在飞行中生成。 该URL的这个组件称为路径组件。
-方法
1 openConnection() 返回一个HTTURLConnection对象 表示远程url引用对象
2 openStream() 以流的形式来获取资源



  • 调用post请求
package com.guonian.miaosha.Scoket;

import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import sun.net.www.http.HttpClient;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.BufferUnderflowException;

/** java中调用http接口的方式
 *  1 httpURLConnnection
 *  2 HttpClient
 *  3 RestTemplate
 * 测试post
 * */
public class HttpInterfacePost {
    public static void main(String[] args) throws Exception {
        HttpURLConnection connection = null;
        PrintWriter pw = null;
        String line = null;


        String target = "http://localhost:8888/menupost";

        //设置url 请求的url
        URL url = new URL(target);
        //设置打开连接 建立连接
        connection=  (HttpURLConnection)url.openConnection();
        //设置请求方式 默认是get
        connection.setRequestMethod("POST");
        //设置通用的请求属性
        connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
        //connection.setRequestProperty("Content-Type", "application/json");


        //post请求不能使用缓存设置为false
        connection.setUseCaches(false);
        //设置是否向connection输出 post请求必须设置
        connection.setDoOutput(true);
        // 设置是否从connection读入,默认情况下是true;  post请求必须设置
        connection.setDoInput(true);


        connection.setConnectTimeout(3000);// 连接主机的超时时间
        connection.setReadTimeout(3000);// 从主机读取数据的超时时间


        //开启连接
        connection.connect();


        //URL获取输出流
        pw = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(),"UTF-8"));
        String params = "name=4&address=123";
        pw.print(params.toString());
        pw.flush();

        System.out.println(connection.getURL());
        System.out.println(connection.toString());


        int responseCode = connection.getResponseCode();
        System.out.println("响应码:"+responseCode);



        if(responseCode == HttpURLConnection.HTTP_OK){
            System.out.println("连接成功!!!");


            String result =null;
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while(null != (result = br.readLine())){
                System.out.println(result);
            }

            //关闭流和关闭连接
            br.close();
            connection.disconnect();
        }else{
            System.out.println("连接失败!!!");
        }

    }
}

  • 请求发送post请求和数据获取
package com.guonian.miaosha.Scoket;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import springfox.documentation.spring.web.json.Json;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;

public class HttpInterfaceMethod {
    public static void main(String[] args) throws JSONException {
        String s = sendPost("http://localhost:8888/menupost", "name=4&address=123");
        JSONArray ja = new JSONArray(s);
        for(int a =0;a<ja.length();a++){
            System.out.println(ja.get(a));
            //将元素变成json对象 强转 
            JSONObject jo = (JSONObject)ja.get(a);
            System.out.println(jo.get("menuId"));
            System.out.println(jo.get("parentId"));
            System.out.println(jo.get("parentIds"));
            System.out.println(jo.get("menuName"));
            System.out.println(jo.get("path"));

        }

    }
    public static String sendPost(String url,String parameter){
        PrintWriter pw = null;
        BufferedReader br = null;
        String result = null;
        HttpURLConnection urlConnection = null;
        try{
            //创建url对象
            URL url1 = new URL(url);
            //建立连接
             urlConnection = (HttpURLConnection)url1.openConnection();
            //设置连接属性
            urlConnection.setRequestProperty("accept", "*/*");
            urlConnection.setRequestProperty("connection", "Keep-Alive");
            urlConnection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //发送post请求必须设置
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);

            //开启连接
            urlConnection.connect();

            //获取连接对象的输出流来拼接参数
            pw = new PrintWriter(urlConnection.getOutputStream());
            pw.write(parameter);
            pw.flush();

            //读取响应数据
            int responseCode = urlConnection.getResponseCode();
            System.out.println("状态码"+responseCode);
            if(responseCode == HttpURLConnection.HTTP_OK){
                System.out.println("响应成功!");
                //获取输入流
                String line = null;
                br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                while(null != (line = br.readLine())){
                    result = line;
                    System.out.println(result);
                }

            }


        }catch(Exception e){
            e.printStackTrace();
        }finally{
            //关闭流和关闭连接
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            urlConnection.disconnect();

        }
        return  result;
    }
}

你可能感兴趣的:(苦练基本功,java)