android api call return simple array - java

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;
}

Related

Pass php var or string to java. Android Studio

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.

Issue with Translation API in Java

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());
}
}

Android - get request received EOFException

Code:
String recipeName = this.recipe.getName().replace(" ", "%20");;
String recipeIngredients = this.recipe.getIngredients().replace(" ", "%20");;
String recipeInstructions = this.recipe.getInstructions().replace(" ", "%20");;
String recipeUserName = this.recipe.getUserName().replace(" ", "%20");;
int recipeRate = this.recipe.getRate();
int recipeAmountOfRate = this.recipe.getAmountOfRates();
String link = "http://***My_Site***/createRecipe.php?recipeName="+recipeName+"&recipeIngredients="+recipeIngredients
+"&recipeInstructions="+recipeInstructions+"&recipeUserName="+recipeUserName+"&recipeRate="+recipeRate+
"&recipeAmountOfRate="+recipeAmountOfRate;
URL url = new URL(link);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setChunkedStreamingMode(0);
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
int ch;
StringBuffer sb = new StringBuffer();
while ((ch = in.read()) != -1) {
sb.append((char) ch);
}
Log.e("Error", sb.toString());
} catch(Exception e) {
Log.e("Error", e.toString());
} finally {
urlConnection.disconnect();
}
}
But i get the error:
E/Error: java.io.EOFException
Why is that?
in previous requests the request went good.
Doed the URL request too long?

Google Distance Matrix not getting distance

I have roughly tried to parse the JSON from Google Distance Matrix API, but it is not showing the distance.
My GPS location is not 0,0 that I'm sure of.
String distance = getMatrix(latitude,longitude);
My code for the function is:
private String getMatrix(double lat , double lang){
JSONObject jObj;
String getdistance = "";
String strUrl = "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
+ Double.toString(my_lat) + ","
+ Double.toString(my_lang)
+ "&destinations="+ Double.toString(lat) + ","
+ Double.toString(lang)
+ "&mode=walking&sensor=false";
String data = "";
InputStream reader = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
reader = urlConnection.getInputStream();
int bRead = -1;
byte[] buffer = new byte[1024];
do {
bRead = reader.read(buffer, 0, 1024);
if (bRead == -1) {
break;
}
data += new String(buffer, 0, bRead);
} while (true);
urlConnection.disconnect();
} catch(Exception e) {
} finally {
}
try {
jObj = new JSONObject(data);
JSONArray rowsArray = jObj.getJSONArray("rows");
JSONObject rows = rowsArray.getJSONObject(0);
JSONArray elementsArray = rows.getJSONArray("elements");
JSONObject newDisTimeOb = elementsArray.getJSONObject(0);
JSONObject distOb = newDisTimeOb.getJSONObject("distance");
getdistance = distOb.optString("text").toString();
} catch (JSONException e) {
e.printStackTrace();
}
return getdistance;
}
First, check if you've correctly build the url string in the code:
String strUrl = "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
+ Double.toString(my_lat) + ","
+ Double.toString(my_lang)
+ "&destinations="+ Double.toString(lat) + ","
+ Double.toString(lang)
+ "&mode=walking&sensor=false";
// Line to check if url code is right
Log.d("APP", "strUrl = " + strUrl);
Then check your following code, whether it really produce the data:
reader = urlConnection.getInputStream();
int bRead = -1;
byte[] buffer = new byte[1024];
do {
bRead = reader.read(buffer, 0, 1024);
if (bRead == -1) {
break;
}
data += new String(buffer, 0, bRead);
} while (true);
My suggestion is to use BufferedReader instead reading the response byte per byte.
Then change:
getdistance = distOb.optString("text").toString();
to
getdistance = distOb.getString("text");
Because you don't need to convert to string again here.
I've search Client Libraries for Google Maps Web Services and found DistanceMatrixApi.java. Maybe we can use it, but I can't assure of it.

XML not parsing completely

I'm trying to extract the xml over Goodread's API, problem is the xml i've extracted is incomplete.
String resultJsonStr = null;
ArrayList<String> results = new ArrayList<String>();
String xml = null;
try {
String str = "https://www.goodreads.com/book/isbn?isbn=9780755380022&key=UpH4L0IYjAXcezlfg0yT2Q";
URL url = new URL(str);
InputStream is = url.openStream();
int ptr = 0;
StringBuilder builder = new StringBuilder();
while ((ptr = is.read()) != -1) {
builder.append((char) ptr);
}
StringBuffer stringBuffer = new StringBuffer(builder);
xml = builder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I'm using this xml
The code stops inside reviews_widget I believe it's reading the thing as a style, and disregarding further lines of the xml.
inside String xml
I'm doing this in preparation for JSON conversion.

Categories

Resources