java后台发送url请求

1、当需要使用其他公司的接口时,前台很可能出现跨域问题,此时就需要后台发送url请求,得到数据后台再返还给前端。
2、代码如下:

public static String getMsg(String url){//url为请求地址
        try {
            JSONObject param = new JSONObject();
                        //param.out("key","value"),添加请求的参数(body)
            param.put("deviceSn", "0011613002A2");
            param.put("fieldId", "66AA");
            param.put("fieldValue", "1");
            StringBuilder sb = new StringBuilder();
            URL urlObj = new URL(url);

            HttpURLConnection conn = (HttpURLConnection)urlObj.openConnection();
            //post请求不能使用缓存
            conn.setUseCaches(false);
            // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此�?��设为true, 默认情况下是false;
            conn.setDoOutput(true);
            // 设置是否从httpUrlConnection读入,默认情况下是true;
            conn.setDoInput(true);
            // 设定请求的方法为"POST",默认是GET
            conn.setRequestMethod("POST");
                        //添加请求头header
            conn.setRequestProperty("token", "token");
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"))){
                writer.write(param.toJSONString());
                writer.flush();
            }
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"))){
                String tmpLine;
                while((tmpLine = reader.readLine()) != null){
                    sb.append(tmpLine);
                }
            }
            conn.disconnect();
            return sb.toString();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

此方法示情况自己修改,url请求地址,param请求参数,conn.setRequestProperty请求头。返回结果为接口返回的字符串。

你可能感兴趣的:(java后台发送url请求)