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.
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 working on a system and need to fetch file from the URL using java URLConnection, Now all i need to copy that contents into excel file.
here is my code.
class getsize {
public static void main(String args[]) throws Exception {
HttpURLConnection conn = null;
try {
String plainCreds = "hmhinstall:hmh201208";
// String url = "http://content.link-systems.com/~hbern/content_update/";
byte[] plainCredsBytes = plainCreds.getBytes();
String base64CredsBytes = Base64.encode(plainCredsBytes);
String base64Creds = base64CredsBytes;
System.out.println(base64Creds);
int code = 0;
URL url = new URL("http://content.link-systems.com/~hbern/content_update/ ");
//Reading
URLConnection uc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
uc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine); //Printing file data
}
in.close();
//Getting size
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + base64Creds);
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setDoOutput(true);
System.out.println(conn.getResponseCode());
System.out.println(conn.getContentType());
conn.getInputStream();
System.out.println("Length : " + conn.getContentLength()); //Getting content length
} catch (Exception exception) {
} finally {
conn.disconnect(); //Disconnect
}
}
}
How can i copy contents of a file in to excel worksheet? So that i can generate records automatically.
thanks in advance
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'm essentially trying to mimic what's been done here through the Android app but for some reason data doesn't get returned as soon as it attempts to post data (it returns fine when I delete the writer.write(finalResult) line).
All I want right now is to be able to search for a user's data once I've sent the username.
Here's my code below:
try {
URL u = new URL(url);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("POST");
c.setRequestProperty("Content-length", "0");
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.setDoInput(true);
c.setDoOutput(true);
//Attempting to send data!
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", paramValue));
OutputStream os = c.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
String finalResult = getQuery(params);
Log.d("params", finalResult);
writer.write(finalResult);
writer.close();
os.close();
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
result = sb.toString();
}
} catch (MalformedURLException ex) {
Log.e("log_tag", "Error converting result ");
} catch (IOException ex) {
Log.e("log_tag", "Error in http connection ");
}
//json code!
//parse json data
try{
JSONArray jArray = new JSONArray(result);
//for each object in our json array
for(int i =0; i < jArray.length(); i++){
JSONObject json_data =jArray.getJSONObject(i);
String address = "";
//Checks for missing data in address - Need a class for all fields
if (json_data.isNull("address")){
address = "N/A";
}
else
{
address = json_data.getString("address");;
}
//read one line of the response
myListView.setText("Username: "+json_data.getString("username")
+" / " + "Name: " + json_data.getString("name")
+" / " + "E-mail: " + json_data.getString("email")
+" / " + "Address: " + address);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data"+e.toString());
}
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
And here is my php script:
<?php
$searchuser = $_GET["username"];
$databasehost = databasehost;
$databasename = database;
$databaseusername = username;
$databasepassword = password;
$con = mysql_connect($databasehost, $databaseusername, $databasepassword) or die(mysql_error());
mysql_select_db($databasename) or die(mysql_error());
$query = "SELECT * FROM testusers";
$sth = mysql_query($query);
if (mysql_errno()) {
header("HTTP/1.1 500 Internal Server Error");
echo $query."\n";
echo mysql_error();
}
else
{
$rows = array();
while ($r = mysql_fetch_assoc($sth)){
$rows[] = $r;
}
print json_encode($rows);
}
?>
Since you set the header Content-Length to be 0, the server doesn't even read your content... So anything you send isn't received. You should set Content-Length to finalResult.length().
remove this,
c.setRequestProperty("Content-length", "0");