目录
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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)