Trying to develop a speech to text application using Google's API with below code
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.testng.annotations.Test;
public class Speech2Text_Test {
#Test
public void f() {
try{
Path path = Paths.get("out.flac");
byte[] data = Files.readAllBytes(path);
String request = "https://www.google.com/"+
"speech-api/v2/recognize?"+
"xjerr=1&client=speech2text&lang=en-US&maxresults=10"+
"output=json&key=<My Key>";
URL url = new URL(request);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "audio/x-flac; rate=16000");
connection.setRequestProperty("User-Agent", "speech2text");
connection.setConnectTimeout(60000);
connection.setUseCaches (false);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.write(data);
wr.flush();
wr.close();
connection.disconnect();
System.out.println("Done");
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
however after running the class (which sends .flac file to Google api) am getting as "{"result":[]}" Instead of the utterances of the audio file converted to text, what could be the cases Google returns the result as "{"result":[]}"?
Ran into the same issue my self. I found that is was the format of the flac file. It needs to be 16-bit PCM and mono otherwise you get the null result back. I use http://www.audacityteam.org/ to check/convert my files.
Related
So I'm trying to make a custom launcher for my custom Minecraft client but I need a session id to launch the game. This is the code I'm using to try and get a session ID:
package net.arachnamc;
import org.json.JSONObject;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
public class Main {
public static void main(String[] args) throws IOException {
String AUTH_SERVER = "https://authserver.mojang.com/authenticate";
String json = String.format(
"{" +
"\"clientToken\":\"%s\"," +
"\"username\":\"%s\"," +
"\"password\":\"%s\"" +
"}",
UUID.randomUUID().toString(),
"Koolade446",
"MyPasswordCensored"
);
JSONObject jso = new JSONObject(json);
System.out.println(json);
URL url = new URL(AUTH_SERVER);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
OutputStream os = urlConnection.getOutputStream();
os.write(json.getBytes(StandardCharsets.UTF_8));
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
urlConnection.disconnect();
}
}
However, the server returns a 403 forbidden every time. I use a Microsoft account but I can't find any documentation on how to authenticate a Microsoft account so I assumed this was it. Any help is appreciated.
I want to match issues in JIRA with other datasource.
I can use curl:
curl -u myname:mypassword
https://jira.myorganization.com/rest/api/latest/issue/TR-1234
This will return info about the issue, for exampel TR-1234, that I want to check some data for.
In java I want to do the same thing but I get javax.net.ssl.SSLHandShakeException
The program I try to run:
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Main {
public static void main(String[] args) {
URL url = null;
try {
url = new URL("https://jira.myorganization.com/rest/api/latest/issue/TR-1234");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
String userpass = "myusername:mypassword";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
con.setRequestProperty ("Authorization", basicAuth);
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
System.out.println("Resp="+ con.getResponseCode()+" "+con.getResponseMessage());
String contentType = con.getHeaderField("Content-Type");
BufferedReader br = new BufferedReader(new InputStreamReader(
(con.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
con.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Can I somehow pass userid and password to the URL. The application is a tool and it would be ok to let the user input his name and password.
I am developing an application in Android Studio, where I will use the registered data of a web system based on PHP and Mysql. I was able to connect with the code below, I also managed to register directly through the application, but how would I do to bring the data in Android using PHP and Mysql?
Connection code
package br.com.perttutigestao.acessosistema;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class Conexao {
public static String postDados(String urlUsuario, String parametrosUsuarios){
URL url;
HttpURLConnection connection = null;
try{
url = new URL(urlUsuario);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Lenght","" + Integer.toString(parametrosUsuarios.getBytes().length));
connection.setRequestProperty("Content-Language","pt-BR");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
outputStreamWriter.write(parametrosUsuarios);
outputStreamWriter.flush();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String linha;
StringBuffer resposta = new StringBuffer();
while ((linha = bufferedReader.readLine()) != null){
resposta.append(linha);
resposta.append('\r');
}
bufferedReader.close();
return resposta.toString();
}catch (Exception erro){
return null;
}finally {
if(connection != null){
connection.disconnect();
}
}
}
}
PHP
<?php
$conexao = mysqli_connect('localhost','root','success','projeto');
$sql = mysqli_query($conexao,"SELECT * FROM pe_mobile");
while($jm = mysqli_fetch_array($sql)){
$mostrar[] = $jm["Email"];
$mostrar[] = $jm["Senha"];
}
echo json_encode($mostrar);
I'm starting to develop in Android and I do not have much experience with Java.
You can try to use Asynctask for getting data from web
I have class which works completely and sends POST request successfully toward the external system.
paramaters which are sent currently in the class are:
username:maxadmin
password:sm
DESCRIPTION: REST API test
Now I want to do copy paste of this class and transform it in that way so I could POST request using the JSON body but I am not sure how to do it.
I saw that I should probably have conn.setRequestProperty("Content-Type", "application/json"); instead of application/x-www-form-urlencoded
Can someone please transform my code in order to POST REQUEST using JSON body for parameters sending instead of URL?
This is my 'URL' working class (you will see username/password are in URL while parameters are send in array I have currently only one attribute DESCRIPTION which I am sending)
package com.getAsset;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.json.*;
public class GETAssetsPOST {
public static String httpPost(String urlStr, String[] paramName,
String[] paramVal) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
for (int i = 0; i < paramName.length; i++) {
writer.write(paramName[i]);
writer.write("=");
writer.write(URLEncoder.encode(paramVal[i], "UTF-8"));
writer.write("&");
}
writer.close();
out.close();
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
public static void main(String[] args) throws Exception {
String[] attr = new String[1];
String[] value = new String[1];
attr[0] = "DESCRIPTION";
value[0] = "REST API test";
String description = httpPost("http://192.168.150.18/maxrest/rest/os/mxasset/123?_lid=maxadmin&_lpwd=sm",attr,value);
System.out.println("\n"+description);
}
}
Thank you
I'm modifying some working code to work with a different provider's API (we are switching helpdesk providers).
I am trying to look at the xml coming back to see if I am even on the right track, but all I see coming back is gibberish. I've looked at this question but can't figure out how those answers might apply to my situation.
If I remember correctly, when I used the other API I was able to read the xml coming back in the console here:
while ((line = br.readLine()) != null) {
System.out.println(line);
}
My question is: Is there a way I can read the stream differently so that I can read the xml that is coming back or do I have another problem?
I'm pretty new to this so any thoughts are appreciated. Further details are below.
Code:
package com.google.gwt.HelpDeskTest.server;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.gwt.HelpDeskTest.client.HelpDeskTestService;
import com.google.gwt.HelpDeskTest.shared.HelpDeskTestException;
#SuppressWarnings("serial")
public class HelpDeskTestImpl extends RemoteServiceServlet implements
HelpDeskTestService {
#Override
public String postToRemoteServer(String serviceUrl)
throws HelpDeskTestException {
try {
final String serverPath= "https://www.myconnectwise.net/v4_6_release/services/system_io/integration_io/processClientAction.rails";
System.out.println(serverPath);
final String serverParameters= "<?xml version=%221.0%22 encoding=%22utf-16%22?>" +
"<GetTicketAction xmlns:xsi=%22http://www.w3.org/2001/XMLSchema-instance%22 xmlns:xsd=%22http://www.w3.org/2001/XMLSchema%22>" +
"<CompanyName>xxxxxx</CompanyName><IntegrationLoginId>xxxxxxx</IntegrationLoginId><IntegrationPassword>xxxxxx</IntegrationPassword>" +
"<SrServiceRecid>1921</SrServiceRecid></GetTicketAction>";
System.out.println(serverParameters);
//Open HttpURLConnection:
URL url = new URL(serverPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000); //added this to see if I can address the timeout issue.
connection.setReadTimeout(10000);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-16");
connection.setRequestProperty("Content-Length", "" + Integer.toString(serverParameters.getBytes().length));
connection.setUseCaches (false);
//connection.setChunkedStreamingMode(0);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(serverParameters);
wr.flush();
wr.close();
//process response - need to get xml response back.
//this was the working line of code:
InputStream stream = connection.getInputStream();
//put output stream into a string
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
String result = "";
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
result+= line;
}
br.close();
connection.disconnect();
System.out.println(result);
return result;
} catch (final Exception e) {
System.out.println(e.getMessage());
throw new HelpDeskTestException();
//handle timeout error
}
}
}
This is the xml I'm attempting to send. I've tested it through the company's API tester and know that it works, and responds by sending xml.
<?xml version="1.0" encoding="utf-16"?>
<GetTicketAction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CompanyName>xxxxxx</CompanyName>
<IntegrationLoginId>xxxxxx</IntegrationLoginId>
<IntegrationPassword>xxxxx</IntegrationPassword>
<SrServiceRecid>1921</SrServiceRecid>
</GetTicketAction>
When you are sending the data you specify utf-16 as encoding.
But when you are reading the response you do not specify an encoding, so the default platform encoding is used.
So exchange this line:
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
with this (assuming the response also is encoded in utf-16):
BufferedReader br = new BufferedReader(new InputStreamReader(stream,"utf-16"));
You should actually check the response header to learn which encoding has been used.
So after much searching I found the answer to this. The xml is read as gibberish because it is Gzip compressed. The way to read this is by using the
GZIPInputStream. This is because the XML is compressed differently.
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Encoding", "gzip");
InputStreamReader in = new InputStreamReader (new GZIPInputStream(connection.getInputStream()));
String str;
while (true) {
int ch = in.read();
if (ch==-1) {
break;
}