一些post请求和get请求的调用例子

目录

post请求

1:http请求,无请求参数,请求包格式为application/json,请求包包含若干字段

get请求

1.http请求,响应类型application/zip,请求结果为下载一个zip的压缩文件

解压下载的压缩包

读取解压后文件的json文件中的数据

         2.get请求,返回json数据


post请求

1:http请求,无请求参数,请求包格式为application/json,请求包包含若干字段

举例:

public String submitFileTransRequestJieTong(String voiceUrl){
    String taskId = "";   // 获取录音文件识别请求任务的ID,以供识别结果查询使用。
    try {
        //请求post
        String urlStr = "http://ip:端口//common/submit?appkey=123&secret=456";
        urlStr = urlStr.replace("\\", "");//
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);//不使用缓存
        connection.setInstanceFollowRedirects(true);
        //设置请求头
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("connection", "keep-alive");
        connection.connect();
        // POST请求,包装成json数据
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        net.sf.json.JSONObject obj = new net.sf.json.JSONObject();
        //files
        net.sf.json.JSONArray arr = new net.sf.json.JSONArray();
        arr.add(voiceUrl);
        //JsonObject中value存放的是数组
        net.sf.json.JSONArray arrVoice = new JSONArray();
        arrVoice.add(".mp3");
        arrVoice.add(".wav");
        obj.element("files", arr);
        obj.element("folder.exts", arrVoice);
        obj.element("folder.paths", voiceUrl);
        obj.element("audioFormat", "auto");
        obj.element("saveTo.path", "");
        obj.element("saveTo.style", "name");
        obj.element("resultType", "JSON");
        out.write(obj.toString());
        out.flush();
        out.close();
        //读取响应
        InputStream is = null;
        int code = connection.getResponseCode();
        if (code >= 400) {
            is = connection.getErrorStream();
        } else {
            is = connection.getInputStream();
        }
        InputStreamReader inputStreamReader = new InputStreamReader(is);
        BufferedReader reader = new BufferedReader(inputStreamReader);
        String lines;
        StringBuffer sb = new StringBuffer("");
        while ((lines = reader.readLine()) != null) {
            lines = new String(lines.getBytes(), "utf-8");
            sb.append(lines);
        }
        //System.out.println(sb);//接口返回结果
        //String转JSONObject
        com.alibaba.fastjson.JSONObject result = com.alibaba.fastjson.JSONObject.parseObject(sb.toString());
        if(result.getInteger("code") == 10200 ){
            System.out.println("文件识别请求成功响应: " + result.toJSONString());
            taskId = result.getString("taskId");
        }else {
            System.out.println("文件识别请求失败: " + result.toJSONString());
        }
        reader.close();
        //断开连接
        connection.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return taskId;

get请求

1.http请求,响应类型application/zip,请求结果为下载一个zip的压缩文件

举例:

public static void getResultDownload(String taskid) throws Exception {
    String url1 = "http://ip:端口/8k_common/download?appkey=123&secret=456&task=";
    String urlTaskid = url1+taskid;
    urlTaskid = urlTaskid.replace("\\", "");
    //filePath 存放下载文件的地址,response.zip是文件名和文件类型
    String filePath = "E:\\testjieTong\\response.zip";
    FileOutputStream fileOut = null;
    HttpURLConnection conn = null;
    InputStream inputStream = null;
    // 建立链接
    try {
        URL httpUrl = new URL(urlTaskid);
        conn=(HttpURLConnection) httpUrl.openConnection();
        //以Post方式提交表单,默认get方式
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        // post方式不能使用缓存
        conn.setUseCaches(false);
        //连接指定的资源
        conn.connect();
        //获取网络输入流
        inputStream=conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        //判断文件的保存路径后面是否以/结尾
        if (!filePath.endsWith("/")) {
            filePath += "/";
        }
        //写入到文件(注意文件保存路径的后面一定要加上文件的名称)
        fileOut = new FileOutputStream(filePath);
        BufferedOutputStream bos = new BufferedOutputStream(fileOut);
        byte[] buf = new byte[4096];
        int length = bis.read(buf);
        //保存文件
        while(length != -1)
        {
            bos.write(buf, 0, length);
            length = bis.read(buf);
        }
        //先开先关原则
        bos.close();
        bis.close();
        conn.disconnect();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

解压下载的压缩包

public static void  zipUncompress() throws Exception{
    File srcFile = new File("E:\\testjieTong\\response.zip");//获取当前压缩文件
    // 判断源文件是否存在
    if (!srcFile.exists()) {
        System.out.println("源文件不存在");
    }
    //开始解压
    //构建解压输入流
    ZipInputStream zIn = new ZipInputStream(new FileInputStream(srcFile));
    ZipEntry entry = null;
    File file1 = null;
    while ((entry = zIn.getNextEntry()) != null) {
        if (!entry.isDirectory()) {
            file1 = new File("E:\\testjieTong\\response", entry.getName());
            if (!file1.exists()) {
                new File(file1.getParent()).mkdirs();//创建此文件的上级目录
            }
            OutputStream out = new FileOutputStream(file1);
            BufferedOutputStream bos = new BufferedOutputStream(out);
            int len = -1;
            byte[] buf = new byte[1024];
            while ((len = zIn.read(buf)) != -1) {
                bos.write(buf, 0, len);
            }
            // 关流顺序,先打开的后关闭
            bos.close();
            out.close();
        }
    }
}

读取解压后文件的json文件中的数据

public static AliResultData readJson(String taskid) throws IOException {
        AliResultData aliResultData = new AliResultData();
            //下载成功,返回数据
            //读取文本
            File filePath = new File("E:\\testjieTong\\response\\0.json");
            long start = System.nanoTime();
//        List<String> keyword = new LinkedList<>();
            Reader reader = new InputStreamReader(new FileInputStream(filePath), "Utf-8");
            //读取每个字符char
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            reader.close();
            String result = sb.toString();
            //System.out.println(result);
//        JSONObject rootObj = JSONObject.parseObject(jsonStr);
//        System.out.println(rootObj);
            aliResultData.setResult(result);
            //以换行符切割字符串
//        String[] str = jsonStr.split("\n");
//        for (int i = 0; i < str.length; i++) {
//            System.out.println(JSONObject.parseObject(str[i]).getString("text"));
//            //将每个字符串转为json对象  JSONObject.parseObject(String str);
//            keyword.add(JSONObject.parseObject(str[i]).getString("text"));
//        }
            //System.out.println(JSONObject.parseObject(jsonStr).getString("text"));
            long end  = System.nanoTime();
            System.out.println("time"+(end-start));

        return aliResultData;
    }

2.get请求,返回json数据

举例:
 

public static String getStatus(String taskid) throws IOException {
    String urlStatus = "http://ip:端口/8k_common/query?appkey=123&secret=456&task=";
    String urlTaskid = urlStatus+taskid;
    urlTaskid = urlTaskid.replace("\\", "");
    URL url = new URL(urlTaskid);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    PrintWriter out = null;
    /**设置URLConnection的参数和普通的请求属性****start***/
    conn.setRequestProperty("accept", "*/*");
    conn.setRequestProperty("connection", "Keep-Alive");
    conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("GET");//GET和POST必须全大写
    conn.connect();
    //获取URLConnection对象对应的输入流
    InputStream is = conn.getInputStream();
    //构造一个字符流缓存
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String str = "";
    while ((str = br.readLine()) != null) {
        str=new String(str.getBytes(),"UTF-8");//解决中文乱码问题
        System.out.println(str);
    }
    //关闭流
    is.close();
    //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
    //固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
    conn.disconnect();
    return str;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 好的,我可以用中文为你讲解如何使用 Node.js 发送 HTTP GET 和 POST 请求。 首先,你需要安装 Node.js 和 npm(Node.js 包管理器)。然后,你可以使用 npm 安装 "request" 模块,这是一个简单易用的 HTTP 客户端库,可以让你轻松发送 HTTP 请求。 安装 "request" 模块的命令如下: ``` npm install request ``` 安装完成后,你就可以在 Node.js 代码中引入 "request" 模块,并使用它发送 HTTP 请求了。 发送 HTTP GET 请求的代码如下: ``` const request = require('request'); request.get('http://www.example.com', (error, response, body) => { if (!error && response.statusCode == 200) { console.log(body); } }); ``` 发送 HTTP POST 请求的代码如下: ``` const request = require('request'); const options = { url: 'http://www.example.com', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, form: { key: 'value', }, }; request(options, (error, response, body) => { if (!error && response.statusCode == 200) { console.log(body); } }); ``` 希望这些信息能帮到你。 ### 回答2: 使用Node.js的http模块可以发送GET和POST请求。 发送GET请求的步骤如下: 1. 首先,我们需要导入http模块,并创建一个服务器对象: ```javascript const http = require('http'); ``` 2. 然后,我们可以使用http模块的get方法发送GET请求: ```javascript const options = { hostname: 'example.com', path: '/api/some-endpoint', method: 'GET' }; const req = http.request(options, (res) => { res.on('data', (data) => { // 处理返回的数据 }); }); req.on('error', (error) => { // 处理请求错误 }); req.end(); ``` 在上面的代码中,我们使用http.request方法创建一个请求对象。我们需要提供一个包含主机名(hostname)、路径(path)和请求方法(method)的选项(options)对象。然后,我们可以通过调用req.end()方法发送请求。当服务器返回数据时,我们可以通过监听'res'对象的'data'事件来处理数据,同时还可以监听'error'事件来处理请求错误。 发送POST请求的步骤类似,只需要设置请求方法为POST,并提供请求体数据。以下是一个发送POST请求例子: ```javascript const postData = JSON.stringify({ username: 'john', password: 'secret' }); const options = { hostname: 'example.com', path: '/api/login', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(postData) } }; const req = http.request(options, (res) => { res.on('data', (data) => { // 处理返回的数据 }); }); req.on('error', (error) => { // 处理请求错误 }); req.write(postData); req.end(); ``` 在上面的例子中,我们设置了请求方法为POST,并提供了请求体数据,即postData。我们还设置了请求头(headers)来指定请求体数据的类型和长度。 以上就是使用Node.js的http模块发送GET和POST请求的基本步骤。 ### 回答3: 使用Node.js中的http模块可以很方便地发送GET和POST请求。 发送GET请求的步骤如下: 1. 首先需要引入http模块:const http = require('http'); 2. 创建一个http请求对象:const options = { hostname: 'www.example.com', // 请求目标的主机名 path: '/api/data', // 请求目标的路径 method: 'GET' // 请求方法为GET }; 3. 发送请求:const req = http.request(options, (res) => { // 处理响应 res.on('data', (data) => { console.log(data.toString()); }); }); req.end(); 发送POST请求的步骤如下: 1. 引入http模块:const http = require('http'); 2. 创建一个http请求对象:const options = { hostname: 'www.example.com', // 请求目标的主机名 path: '/api/data', // 请求目标的路径 method: 'POST', // 请求方法为POST headers: { 'Content-Type': 'application/json' // 请求头设置为JSON格式 } }; 3. 创建一个POST请求体:const postData = JSON.stringify({name: 'John', age: 25}); 4. 发送请求:const req = http.request(options, (res) => { // 处理响应 res.on('data', (data) => { console.log(data.toString()); }); }); req.write(postData); // 将请求体写入请求 req.end(); 以上就是使用Node.js的http模块发送GET和POST请求的简单示例。根据具体需求,可以对请求头和请求体进行更多的定制。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值