Golang 建立RESTful webservice 接收客户端POST请求发送wav语音文件

简介:

   首先看下服务器端,服务器端使用martini框架,仅建立一个简单的接收客户端post请求并保存客户端传过来的语音的后台服务:

   原文地址:http://liuxp0827.blog.51cto.com/5013343/1412977

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package  main
                         
//http://liuxp0827.blog.51cto.com/5013343/1412977                                                                                         
                       
import  (
     "bufio"
     "github.com/go-martini/martini"
     "io/ioutil"
     "log"
     "net/http"
     "os"
)
                                                                                                                                                                                                   
func main() {
     m := martini.Classic()
                                                                                                                                                                                                   
     m.Post( "/wave" , func(req *http.Request) {
         file, _, err := req.FormFile( "file" )
         if  err != nil {
             log.Fatal( "FormFile: " , err.Error())
             os.Exit( 2 )
         }
         defer func() {
             if  err := file.Close(); err != nil {
                 log.Fatal( "Close: " , err.Error())
                 os.Exit( 2 )
             }
         }()
                                                                                                                                                                                                   
         localFile, _ := os.Create( "1.wav" )
         defer localFile.Close()
         writer := bufio.NewWriter(localFile)
         bytes, err := ioutil.ReadAll(file)
         if  err != nil {
             log.Fatal( "ReadAll: " , err.Error())
             os.Exit( 2 )
         }
                                                                                                                                                                                                   
         writer.Write(bytes)
         writer.Flush()
     })
                                                                                                                                                                                                   
     http.ListenAndServe( ":8080" , m)
}

   再来看下客户端的java代码,首先调用readWavform函数从本地读取语音文件到byte[],然后设置相应的POST头信息,最终发送数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import  java.io.ByteArrayOutputStream;
import  java.io.File;
import  java.io.FileInputStream;
import  java.io.FileNotFoundException;
import  java.io.IOException;
import  java.io.InputStream;
import  java.io.OutputStream;
import  java.net.HttpURLConnection;
import  java.net.URL;
import  java.util.HashMap;
import  java.util.Iterator;
import  java.util.Map;
                                                                                          
                     
//http://liuxp0827.blog.51cto.com/5013343/1412977
                                                               
public  final  class  upload {
                                                                                                                                   
     public  static  void  main(String[] args) {
         Map<String, String> parameters =  new  HashMap<String, String>();                                                                
         byte [] data = readWavform( "C:\\Users\\PONPON\\Desktop\\test.wav" );
         doUploadFile( "http://localhost:8080/wave" , parameters,
                 Constants.FILEPARAM,  "11.wav" "multipart/form-data;" ,
                 data);
     }
                                                                                                                                   
     public  static  byte [] readWavform(String filename) {
                                                                                                                                   
         int  regLen =  0 ;
         byte [] regbuffer =  null ;
         try  {
             FileInputStream inputsteam =  new  FileInputStream( new  File(filename));
                                                                                                                                   
             regLen = inputsteam.available();
             regbuffer =  new  byte [regLen];
             if  ((regLen = inputsteam.read(regbuffer,  0 , regLen)) <  0 ) {
                 System.out.println( "error when read pcm file." );
             }
                                                                                                                                   
         catch  (FileNotFoundException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         catch  (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
                                                                                                                                   
         return  regbuffer;
     }
                                                                                                                                   
     public  static  String doUploadFile(String reqUrl,
             Map<String, String> parameters, String fileParamName,
             String filename, String contentType,  byte [] data) {
         HttpURLConnection urlConn =  null ;
         try  {
             urlConn = sendFormdata(reqUrl, parameters, fileParamName, filename,
                     contentType, data);
             String responseContent =  new  String(getBytes(urlConn));
             return  responseContent.trim();
         catch  (Exception e) {
             throw  new  RuntimeException(e.getMessage(), e);
         finally  {
             if  (urlConn !=  null ) {
                 urlConn.disconnect();
             }
         }
     }
                                                                                                                                   
     private  static  HttpURLConnection sendFormdata(String reqUrl,
             Map<String, String> parameters, String fileParamName,
             String filename, String contentType,  byte [] data) {
         HttpURLConnection urlConn =  null ;
         try  {
             URL url =  new  URL(reqUrl);
             urlConn = (HttpURLConnection) url.openConnection();
             urlConn.setRequestMethod( "POST" );
             urlConn.setConnectTimeout( 10000 ); // (单位:毫秒)jdk
             urlConn.setReadTimeout( 10000 ); // (单位:毫秒)jdk 1.5换成这个,读操作超时
             urlConn.setDoOutput( true );
             urlConn.setRequestProperty( "connection" "keep-alive" );
                                                                                                                                   
             String boundary =  "-----------------------------114975832116442893661388290519" // 分隔符
             urlConn.setRequestProperty( "Content-Type" ,
                     "multipart/form-data; boundary="  + boundary);
                                                                                                                                   
             boundary =  "--"  + boundary;
             StringBuffer params =  new  StringBuffer();
             if  (parameters !=  null ) {
                 for  (Iterator<String> iter = parameters.keySet().iterator(); iter
                         .hasNext();) {
                     String name = iter.next();
                     String value = parameters.get(name);
                     params.append(boundary +  "\r\n" );
                     params.append( "Content-Disposition: form-data; name=\""
                             + name +  "\"\r\n\r\n" );
                     params.append(value);
                     params.append( "\r\n" );
                 }
             }
             StringBuilder sb =  new  StringBuilder();
             sb.append(boundary);
             sb.append( "\r\n" );
             sb.append( "Content-Disposition: form-data; name=\""  + fileParamName
                     "\"; filename=\""  + filename +  "\"\r\n" );
             sb.append( "Content-Type: "  + contentType +  "\r\n\r\n" );
             byte [] fileDiv = sb.toString().getBytes( "UTF-8" );
             byte [] endData = ( "\r\n"  + boundary +  "--\r\n" ).getBytes( "UTF-8" );
             byte [] ps = params.toString().getBytes( "UTF-8" );
             OutputStream os = urlConn.getOutputStream();
             os.write(ps);
             os.write(fileDiv);
             os.write(data);
             os.write(endData);
             os.flush();
             os.close();
         catch  (Exception e) {
             throw  new  RuntimeException(e.getMessage(), e);
         }
         return  urlConn;
     }
     private  static  byte [] getBytes(HttpURLConnection urlConn) {
         try  {
             InputStream in = urlConn.getInputStream();
             ByteArrayOutputStream os =  new  ByteArrayOutputStream();
             byte [] buf =  new  byte [ 1024 ];
             for  ( int  i =  0 ; (i = in.read(buf)) >  0 ;)
                 os.write(buf,  0 , i);
             in.close();
             return  os.toByteArray();
         catch  (Exception e) {
             throw  new  RuntimeException(e.getMessage(), e);
         }
     }
}

   这只是简单的功能实现,后面可以用martini拓展,写一个简单的web语音识别服务,用android录音后发送POST请求,把语音数据发送到服务器处理识别,再返回json格式的识别结果。










本文转自 ponpon_ 51CTO博客,原文链接:http://blog.51cto.com/liuxp0827/1412977,如需转载请自行联系原作者
目录
相关文章
|
XML JSON 数据格式
flea-jersey使用之Flea RESTful接口客户端接入
本篇介绍 Flea框架下的 flea-jersey-client模块,并提供客户端依赖管理及接入步骤
124 1
flea-jersey使用之Flea RESTful接口客户端接入
|
NoSQL 安全 Go
Golang 官方推荐使用的 Redis 客户端 redigo
Golang 官方推荐使用的 Redis 客户端 redigo
409 0
|
存储 JSON Go
Golang 语言 gRPC 服务怎么同时支持 gRPC 和 HTTP 客户端调用?
Golang 语言 gRPC 服务怎么同时支持 gRPC 和 HTTP 客户端调用?
326 0
|
消息中间件 自然语言处理 Go
Golang 语言编写的消息队列 NSQ 官方客户端 go-nsq 怎么使用?
Golang 语言编写的消息队列 NSQ 官方客户端 go-nsq 怎么使用?
210 0
|
XML 物联网 API
服务端和客户端 RESTful 接口上传 Excel 的 Python 代码
本文作者木头左是物联网工程师,分享如何使用 Python 和 Flask-RESTful 构建一个简单的 RESTful API,实现文件上传功能,特别支持Excel文件。通过安装Flask和Flask-RESTful库,创建Flask应用,实现文件上传接口,并将其添加到API。该方法具有简单易用、灵活、可扩展及社区支持等优点。
服务端和客户端 RESTful 接口上传 Excel 的 Python 代码
|
JSON Go API
使用Go语言和Gin框架构建RESTful API:GET与POST请求示例
使用Go语言和Gin框架构建RESTful API:GET与POST请求示例
|
消息中间件 Java Kafka
Golang 语言中 kafka 客户端库 sarama
Golang 语言中 kafka 客户端库 sarama
583 0
|
API C# 开发框架
WPF与Web服务集成大揭秘:手把手教你调用RESTful API,客户端与服务器端优劣对比全解析!
【8月更文挑战第31天】在现代软件开发中,WPF 和 Web 服务各具特色。WPF 以其出色的界面展示能力受到欢迎,而 Web 服务则凭借跨平台和易维护性在互联网应用中占有一席之地。本文探讨了 WPF 如何通过 HttpClient 类调用 RESTful API,并展示了基于 ASP.NET Core 的 Web 服务如何实现同样的功能。通过对比分析,揭示了两者各自的优缺点:WPF 客户端直接处理数据,减轻服务器负担,但需处理网络异常;Web 服务则能利用服务器端功能如缓存和权限验证,但可能增加服务器负载。希望本文能帮助开发者根据具体需求选择合适的技术方案。
796 0
|
监控 测试技术 API
|
Go 开发者
golang的http客户端封装
golang的http客户端封装
360 0

推荐镜像

更多