请求地址:http://japi.juhe.cn/voice_words/getWords

此接口必须用POST请求,java网络请求有HttpClient相关工具包及HttpURLConnection相关的包等,这里用的是HttpClient,需要先导包,如果用maven话会更方便直接把下面的复制到pom.xml:org.apache.httpcomponentshttpmime4.3.6org.apache.httpcomponentshttpclient4.4.1

请求代码如下:package com.jefferson.utils.interfaceDemo.voice_words;

import java.io.File;

import org.apache.commons.io.IOUtils;

import org.apache.http.HttpEntity;

import org.apache.http.client.config.RequestConfig;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.ContentType;

import org.apache.http.entity.mime.MultipartEntityBuilder;

import org.apache.http.entity.mime.content.FileBody;

import org.apache.http.entity.mime.content.StringBody;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

public class Voice_words {

private static RequestConfig config = RequestConfig.custom()

.setConnectTimeout(30000).setSocketTimeout(30000).build();

private static String key = "";

public static void main(String[] args) throws Exception {

File file = new File("E:\\wave\\test.wav");

String rate ="8000";

System.out.println(voice_words( rate, file));

}

private static String voice_words(String rate,File file) throws Exception{

CloseableHttpClient httpClient = HttpClients.createDefault();

CloseableHttpResponse response = null;

String result =null;

try {

HttpPost httppost = new

HttpPost("http://japi.juhe.cn/voice_words/getWords");

FileBody bin = new FileBody(file);

StringBody keyBody = new StringBody(key, ContentType.TEXT_PLAIN);

StringBody rateBody = new StringBody(rate, ContentType.TEXT_PLAIN);

HttpEntity reqEntity = MultipartEntityBuilder.create()

.addPart("file", bin)

.addPart("key", keyBody)

.addPart("rate", rateBody).build();

httppost.setEntity(reqEntity);

httppost.setConfig(config);

response = httpClient.execute(httppost);

HttpEntity resEntity = response.getEntity();

if (resEntity != null) {

result =IOUtils.toString(resEntity.getContent(), "UTF-8");

}

EntityUtils.consume(resEntity);

} finally {

if(response!=null){

response.close();

}

httpClient.close();

}

return result;

}

}

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐