一些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
    评论
Sure! Here's an example of how to send a POST request using HttpClient in Java: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) { HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost = new HttpPost("http://www.example.com/api/endpoint"); try { // Add request headers httpPost.setHeader("Content-Type", "application/json"); // Add request body String requestBody = "{\"key1\":\"value1\", \"key2\":\"value2\"}"; StringEntity stringEntity = new StringEntity(requestBody); httpPost.setEntity(stringEntity); // Send the POST request HttpResponse response = httpClient.execute(httpPost); // Get the response body HttpEntity responseEntity = response.getEntity(); String responseBody = EntityUtils.toString(responseEntity); // Print the response body System.out.println(responseBody); } catch (Exception e) { e.printStackTrace(); } } } ``` In this example, we're using the Apache HttpClient library to send a POST request to `http://www.example.com/api/endpoint`. We set the request headers, add the request body as a JSON string, and then execute the request using `httpClient.execute(httpPost)`. Finally, we retrieve the response body from the `HttpResponse` object and print it out. Remember to replace `http://www.example.com/api/endpoint` with the actual URL you want to send the POST request to, and modify the request headers and body according to your requirements.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值