i am trying to translate from english into Arabic using translate.googleapis.com.
it works well with all letters except one letter it always show letter 'ف' as '�?'
any suggestions ?
private static String callUrlAndParseResult(String langFrom, String langTo, String word) throws Exception {
String url =
"https://translate.googleapis.com/translate_a/single?" + "client=gtx&" + "sl=" + langFrom + "&tl=" +
langTo + "&dt=t&q=" + URLEncoder.encode(word, "UTF-8");
URL obj = new URL(url);
URLConnection con = obj.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return parseResult(response.toString());
}
private static String parseResult(String inputJson) throws Exception {
/*
* inputJson for word 'hello' translated to language Hindi from English-
* [[["??????","hello",,,1]],,"en"]
* We have to get '?????? ' from this json.
*/
JSONArray jsonArray = new JSONArray(inputJson);
JSONArray jsonArray2 = (JSONArray) jsonArray.get(0);
JSONArray jsonArray3 = (JSONArray) jsonArray2.get(0);
return jsonArray3.get(0).toString();
}
public static void main(String[] args) {
try {
String word = callUrlAndParseResult("en", "ar", "phone");
System.out.println(new String(word.getBytes(), Charset.forName("UTF-8")));
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
i am using jdeveloper 12cR2
Please note that whenever you use Reader, there will be conversions between charsets. If you do not specify your charset, it will use the system default charset to encode the incoming byte stream, and you would get into trouble if the incoming byte stream is actually not in the same charset with your system.
Therefore, it is advised to specific the charset when using Reader.
So your code should like below.
private static String callUrlAndParseResult(String langFrom, String langTo, String word) throws Exception {
String url =
"https://translate.googleapis.com/translate_a/single?" + "client=gtx&" + "sl=" + langFrom + "&tl=" +
langTo + "&dt=t&q=" + URLEncoder.encode(word, "UTF-8");
URL obj = new URL(url);
URLConnection con = obj.openConnection();
con.setRequestProperty("User-Agent", "Mozilla/5.0");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return parseResult(response.toString());
}
private static String parseResult(String inputJson) throws Exception {
/*
* inputJson for word 'hello' translated to language Hindi from English-
* [[["??????","hello",,,1]],,"en"]
* We have to get '?????? ' from this json.
*/
JSONArray jsonArray = new JSONArray(inputJson);
JSONArray jsonArray2 = (JSONArray) jsonArray.get(0);
JSONArray jsonArray3 = (JSONArray) jsonArray2.get(0);
return jsonArray3.get(0).toString();
}
public static void main(String[] args) {
try {
String word = callUrlAndParseResult("en", "ar", "phone");
System.out.println(word);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
Related
I'm trying to use the PUBG API (popular PC game) and I am having trouble using JSON (first time). I just want to access figures that are further embedded within the JSON array.
I have tried accessing index numbers of the JSON array but it seemed to not work
Here is the JSON im trying to use
![1]: https://imgur.com/dGy4k9t "json"
Here is what I've tried
public static void main(String[] args) {
StringBuffer response = new StringBuffer();
try {
URL url = new URL("https://api.pubg.com/shards/steam/seasons/lifetime/gameMode/squad-fpp/players?filter[playerIds]=account.0165929b76b147d1a453bbfd21a58b4b");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Bearer " + API_KEY);
conn.setRequestProperty("Accept", "application/vnd.api+json");
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("============");
System.out.println("============");
JSONObject myResponse = new JSONObject(response.toString());
JSONArray arr = myResponse.getJSONArray("data");
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("type");
System.out.println("name: " + post_id);
}
}
I'm not really sure how to do go about passing a variable from PHP to Java. I'd like to do the business logic in Java. I'd like to pass a variable $result from the PHP script dupCreateAccount.php.
<?php
require "db.php";
if(mysqli_num_rows($resultName) > 0 || mysqli_num_rows($resultEmail) > 0)
{
$result = "ex";
}
else
{
$result = "b";
}
if( count_chars($password) < 6)
{
$result = "bP";
}
echo (string) $result;
?>
This the php code. When I echo the results I can see the strings when running the android emulator.
protected String doInBackground(String... voids) {
String type = voids[3];
String checkUsername_url = "http://localhost/dupCreateAccount.php";
if(type.equals("Validate"))
{
try {
String user = voids[0];
String email = voids[1];
String password = voids [2];
URL url = new URL(checkUsername_url);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream outputStream = httpConn.getOutputStream();
BufferedWriter buffWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_date = URLEncoder.encode("user", "UTF-8") + "="+URLEncoder.encode(user,"UTF-8") + "&"
+ URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email, "UTF-8") + "&"
+ URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password, "UTF-8");
buffWriter.write(post_date);
buffWriter.flush();
buffWriter.close();
outputStream.close();
InputStream is = httpConn.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(is, "iso-8859-1"));
String result = "";
String line;
while((line = bf.readLine()) != null)
{
result += line;
}
bf.close();
is.close();
httpConn.disconnect();
return result;
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPostExecute(String result) {
if(result.equals("b"))
result = "bad username or email";
if(result.equals("bP"))
result = "bad password";
alert.setMessage(result + " on Crack Execute here");
alert.show();
}
What I was thinking was that when I return the variable result in PHP it gets sent too the OnPostExecute method. But I don't that's right. I'm not sure what step I'm missing .
EDIT: So the php result gets passed to java. But the problem i'm having is messing with the String result after it's passed. In the OnPostExecute method the equals method doesn't do anything.
I am creating a translator app where I am getting the input text from android supported voice Recognizer. Example : Hindi, Chinese, etc. Now I want to build the query like this -
public JSONObject getTranslatedText() {
StringBuilder sb = new StringBuilder();
String http = "https://translation.googleapis.com/language/translate/v2?key=xyz";
JSONObject response = null;
String json = "";
HttpURLConnection urlConnection = null;
try {
URL url = new URL(http);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.connect();
String line1 = "{\n" + " 'q': '" + inputString + "',\n" + " 'target': '" + targetcodeString + "'\n" + "}";
DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
out.writeBytes(line1);
out.flush();
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
json = sb.toString();
response = new JSONObject(json);
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (JSONException e) {
} finally {
if (urlConnection != null) urlConnection.disconnect();
}
return response;
}
The problem is it is not encoding properly and I am getting output like this -
Example: For a word "How are you" in Hindi i.e "क्या हाल" as 9 & HG 08 * E
Can I get some help please. Thanks in advance.
Try using Html.fromHtml(yourTranslatedStr).toString().
I tried that with Hindi and it worked.
how can i access to number of search result in bing search?
i found this thread:
How to get number of search result from Bing API
in this thread i understand that i should use d->results[0]->WebTotal
but how can i use this line in java?
public static void main(String[] args) throws Exception {
//term1
String searchText = "is";
searchText = searchText.replaceAll(" ", "%20");
String accountKey="WOCKN8uXArczOkQq5phtoEc7usB0kDoPTnbqn0sKWeg";
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
URL url;
try {
url = new URL(
"https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Web?Query=%27" + searchText + "%27&$top=50&$format=Atom");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
//conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
System.out.println("Output from Server .... \n");
char[] buffer = new char[4096];
while ((output = br.readLine()) != null) {
sb.append(output);
//text.append(link + "\n\n\n");//Will print the google search links
//}
}
conn.disconnect();
int find = sb.indexOf("<d:Description");
int total = find + 1000;
System.out.println("Find index: " + find);
System.out.println("Total index: " + total);
sb.getChars(find+35, total, buffer, 0);
String str = new String(buffer);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
http://learn-it-stuff.blogspot.com/2012/09/using-bing-custom-search-inside-your.html
I found the answer:
public static void main(String[] args) {
String searchText = "searchtext";
searchText = searchText.replaceAll(" ", "%20");
String accountKey="key_ID";
byte[] accountKeyBytes = Base64.encodeBase64((accountKey + ":" + accountKey).getBytes());
String accountKeyEnc = new String(accountKeyBytes);
URL url;
try {
url = new URL(
"https://api.datamarket.azure.com/Bing/Search/v1/Composite?Sources=%27Web%27&Query=%27" + searchText + "%27&$format=JSON");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
StringBuilder sb = new StringBuilder();
String output;
System.out.println("Output from Server .... \n");
//write json to string sb
while ((output = br.readLine()) != null) {
sb.append(output);
}
conn.disconnect();
//find webtotal among output
int find= sb.indexOf("\"WebTotal\":\"");
int startindex = find + 12;
int lastindex = sb.indexOf("\",\"WebOffset\"");
System.out.println(sb.substring(startindex,lastindex));
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
i am calling an api which should return an array of length between 0 to 9. Now i am not understanding how to get that array. for getting simple string other api's
My code is:are working fine according to this code.
private String test(String url)
{
String str = null;
int c;
try
{
URL hp = new URL(url); //The String hp1 is passed in URL
URLConnection hpCon = hp.openConnection();
hpCon.setUseCaches(false);
hpCon.setConnectTimeout(10000);
System.out.println("*url content for: " + url);
InputStream input=hpCon.getInputStream();
StringBuffer sb = new StringBuffer();
while(((c=input.read())!= -1))
{
sb.append((char)c);
}
str=sb.toString();
sb = null;
//System.out.print(str);
input.close();
input = null;
hpCon = null;
hp = null;
}
catch(Exception e)
{
}
return str;
}