How can I get youtubeVideo Title from URL for android studio? - java

I want to get the youtube video title from a url so I found this code below (IOUtils) is depreciated any other way to do this
public class SimpleYouTubeHelper {
public static String getTitleQuietly(String youtubeUrl) {
try {
if (youtubeUrl != null) {
URL embededURL = new URL("http://www.youtube.com/oembed?url=" +
youtubeUrl + "&format=json"
);
return new JSONObject(IOUtils.toString(embededURL)).getString("title");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
second way i tried
class getYoutubeJSON extends Thread {
String data = " ";
#Override
public void run() {
try {
URL url = new URL("http://www.youtube.com/oembed?url="+" https://www.youtube.com/watch?v=a4NT5iBFuZs&ab_channel=FilipVujovic"
+ "&format=json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null){
data =data + line;
}
if(!data.isEmpty()){
JSONObject jsonObject = new JSONObject(data);
// JSONArray users = jsonObject.getJSONArray("author_name");
Log.d("RT " , jsonObject.toString());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This code gets a an error Cleartext HTTP traffic to www.youtube.com not permitted
so I found this answer Android 8: Cleartext HTTP traffic not permitted but I am still getting some error I don't understand.

I solved this problem by using the volley library.
My requested url was:
String Video_id = "jhjgN2d7yok";
String url = "https://www.youtube.com/oembed?url=youtube.com/watch?v=" +Video_id+ "&format=json";

Related

HTTP response not giving output

I am working on an application that interacts with a room security control device.
I want to get devices information from API. I am using HttpUrlConnection and POST method. It hits the API and I get 200 OK response but I get the out
"{"json":{"control":{"cmd":"getdevice","uid":256}}} doesn't exist"
I have tried all the solutions from stackoverflow and other platforms but it's not giving the output.
Moreover I have tested this API on Postman and it's working there and giving the device information.
Here is the code:
public class HTTPRequestTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
String username = "admin";
String password = "888888";
URL url = null;
try {
url = new URL("http://192.168.100.25/network.cgi");
} catch (MalformedURLException e) {
e.printStackTrace();
}
assert url != null;
HttpURLConnection httpRequest = null;
try {
httpRequest = (HttpURLConnection) url.openConnection();
httpRequest.setRequestMethod("POST");
httpRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpRequest.setDoInput(true);
httpRequest.setDoOutput(true);
android.util.Base64.encode(authString.getBytes(), android.util.Base64.DEFAULT);
httpRequest.addRequestProperty("Authorization", "Basic " + "YWRtaW46ODg4ODg4"); // This is auth bytecode
httpRequest.connect();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
JSONObject json = new JSONObject();
JSONObject jsonObject = new JSONObject();
JSONObject jsonObjectControl = new JSONObject();
jsonObjectControl.put("cmd","getdevice");
jsonObjectControl.put("uid",256);
jsonObject.put("control",jsonObjectControl);
json.put("json", jsonObject);
String encodedData = URLEncoder.encode( json.toString(), "UTF-8" );
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpRequest.getOutputStream()));
writer.write(encodedData);
writer.flush();
BufferedReader bufferedReader = null;
bufferedReader = new BufferedReader
(new InputStreamReader(httpRequest.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
do {
line = bufferedReader.readLine();
sb.append(line);
Log.i("Output line: ",sb.toString());
}
while(bufferedReader.readLine()!=null);
bufferedReader.close();
int responseCode = httpRequest.getResponseCode();
String resMsg = httpRequest.getResponseMessage();
String result = sb.toString();
Log.d("Output: ","--"+result);
Log.d("Response Code: "+responseCode, "!!");
Log.d("Response MSG ","--"+resMsg);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}

Android Studio crash google Geo Api

I'm having a little problem with my app. It crashes and when I run it on Debug it doesn't say anything. This is where the crash occurs:
public class GeoTask extends AsyncTask<String,Void,ArrayList<Double>>{
#Override
protected ArrayList<Double> doInBackground(String... params) {
ArrayList<Double> geo_ll = new ArrayList<>();
HttpsURLConnection connection = null;
BufferedReader reader = null;
String result ="";
try {
URL url = new URL("https://maps.googleapis.com/maps/api/geocode/json?address=New York&key=AIzaSyBpaGooTWbj7QbN_qdW4pf-OvAi2OOhpG4");
connection = (HttpsURLConnection) url.openConnection();
int code = connection.getResponseCode();
int a = 1;
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK){
return null;
}
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = reader.readLine();
while(line!=null){
result+=line;
line = reader.readLine();
}
JSONObject object = new JSONObject(result);
JSONArray results = object.getJSONArray("results");
JSONObject zero = results.getJSONObject(0);
JSONObject geometry = zero.getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
double latitude = location.getDouble("lat");
double longitude = location.getDouble("lng");
geo_ll.add(latitude);
geo_ll.add(longitude);
return geo_ll;
} catch (MalformedURLException e) {
Toast.makeText(NewItemActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
Toast.makeText(NewItemActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(NewItemActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
return null;
}
I can't see anything wrong. I have checked it more then 100 times and still it happens. It actually worked once and then never worked again after...
please help.
thank you for your time.

Android: Parse json using httpurlconnection [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
I am using httpurlconnection and I can't find understandeble way to parse my json.
attribute output return this json {"value":"SUCCESS"}
but how to parse the json?
code
protected Void doInBackground(String... params) {
String ue=params[1];
try {
//final TextView outputView = (TextView) findViewById(R.id.showOutput);
URL url = new URL("my url return json ");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
String urlParameters = "e="+ue;
connection.setRequestMethod("POST");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
connection.setDoOutput(true);
DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
dStream.writeBytes(urlParameters);
dStream.flush();
dStream.close();
int responseCode = connection.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
final StringBuilder output = new StringBuilder("Request URL " + url);
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder responseOutput = new StringBuilder();
System.out.println("output===============" + br);
while((line = br.readLine()) != null ) {
responseOutput.append(line);
}
br.close();
output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());
register.this.runOnUiThread(new Runnable() {
#Override
public void run() {
//output;
try {
JSONObject json = new JSONObject(output.toString());
message = json.optString("value");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(register.this,"output: "+output, Toast.LENGTH_SHORT).show();
progress.dismiss();
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute() {
progress.dismiss();
}
if there is any dependences that I should to add to gradel.Please, let me know! thank you in advance
Simplest way:
try {
JSONObject json = new JSONObject(output); // output string
String message = json.optString("value"); // SUCCESS
} catch (JSONException e) {
e.printStackTrace();
}
But I would recommend to use Gson.

PHP URL is working on broswer but when i tried to run it from my android application InputStream is null

I new to android and want to call web service written in PHP from android application; but I am getting InputStream as null. But when I tried to run same URL from browser it is showing the output.
My php file: (userlogin.php)
<?php
$con=mysqli_connect("IP Address of server","Any","","user");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_GET['username'];
$password = $_GET['password'];
$result = mysqli_query($con,"SELECT * FROM userLogin where username = '$username' and password = '$password'");
$n_filas = mysqli_num_rows ($result);
$array = array();
for ($i=0; $i<$n_filas; $i++)
{
$fila = mysqli_fetch_array($result);
$array[$i]['username'] = utf8_encode($fila['username']);
$array[$i]['password'] = utf8_encode($fila['password']);
}
$result= json_encode($array);
echo $result;
mysqli_close($con);
?>
and my JSON parser :
public JSONArray makeHttpRequest(String url, ArrayList<String> params) {
try
{
URL url1 = new URL("http://IP ADDRESS OF SERVER/userlogin.php?username="+params.get(0)+"&password="+params.get(1));
urlConnection = (HttpURLConnection) url1.openConnection();
urlConnection.connect();
is = urlConnection.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
Log.d("String is",is.toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.d("String ===",json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try
{
Log.d("In JSON Object try ", "yes");
jObj = new JSONArray(json);
Log.d("String Json ===",jObj.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
Any help will be appreciated. Thank You.
The following works for me:
public static void retrieveData() {
try {
// the following line is BAD - do not supply username + password via such an insecure connection!
URL url1 = new URL("http://IP ADDRESS OF SERVER/userlogin.php?username="+params.get(0)+"&password="+params.get(1));
URLConnection urlConnection = url1.openConnection();
// you may want to adjust the timeout here, like so:
// urlConnection.setConnectTimeout(timeout);
urlConnection.connect();
try (InputStream is = urlConnection.getInputStream()) {
processData(is);
} catch (IOException e) {
// do something smart
}
} catch (MalformedURLException e) {
// do something smart
} catch (IOException e) {
// do something smart
}
}
private static void processData(InputStream is) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// rest of your processing logic
} catch (IOException e) {
// do something smart
}
}
These methods do not necessarily have to be static and you may of course amend their signature (parameters, return value) to suit your needs.

Android: download .html and convert it to String

I need to download .html file from some URL. How can I do it? And how can I convert it to String?
UPDATED:
I have no idea why you downvoting. I can get the desired result on iOS by only using one method stringWithContentsOfURL:encoding:error:. And I suggested that Android has similar. method
Code below downloads html page from link, and return html page converted to string in completion callback
public class HTMLPageDownloader extends AsyncTask<Void, Void, String> {
public static interface HTMLPageDownloaderListener {
public abstract void completionCallBack(String html);
}
public HTMLPageDownloaderListener listener;
public String link;
public HTMLPageDownloader (String aLink, HTMLPageDownloaderListener aListener) {
listener = aListener;
link = aLink;
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(link);
String html = "";
try {
HttpResponse response = client.execute(request);
InputStream in;
in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line);
}
in.close();
html = str.toString();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return html;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (!isCancelled()) {
listener.completionCallBack(result);
}
}
}
How's this:
URL url;
InputStream is = null;
DataInputStream dis;
String line;
String out = "";
try {
url = new URL("http://www.example.com/");
is = url.openStream(); // throws an IOException
dis = new DataInputStream(new BufferedInputStream(is));
while ((line = dis.readLine()) != null) {
out.append(line);
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
is.close();
} catch (IOException ioe) {
}
}
You can use http://jsoup.org library
or
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
}finally {
urlConnection.disconnect();
}
and covert Input Stream to String
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
br.close();
You could use HttpURLConnection, streams, and a ReadableByteChannel.
I feel this helps down the line for adding request info to the connection.
try {
URL test = new URL(/* link to your resource */);
HttpURLConnection httpcon = (HttpURLConnection) test.openConnection();
httpcon.addRequestProperty("User-Agent", "Mozilla/5.0");
ReadableByteChannel rbc = Channels.newChannel(httpcon.getInputStream());
FileOutputStream fos = new FileOutputStream(/* File output here */);
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
fos.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}

Categories

Resources