I try to download an image via bing image search api. I get an error after open the connection to the endpoint:
java.io.FileNotFoundException: https://api.cognitive.microsoft.com/bing/v7.0/images/search?q=Der+Rueckkehrer+Bluray
Here my code:
String subscriptionKey = "my sub key";
String host = "https://api.cognitive.microsoft.com";
String path = "/bing/v7.0/images/search";
URL url = new URL(host + path + "?q=" + URLEncoder.encode(productName, "UTF-8"));
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
connection.setRequestProperty("Ocp-Apim-Subscription-Key", subscriptionKey);
System.out.println("URL " + url);
// receive JSON body
InputStream stream = connection.getInputStream(); <--- Crash
bingResult = readStream(stream);
Related
I'm trying to get the data from this google translate API URL:
String sourceLang = "auto";
String targetLang = "en";
String sourceText = "olas";
String urlstring = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" + sourceLang + "&tl=" + targetLang + "&dt=t&q=" + sourceText;
the api url works good on python, but on android i get the filenotfoundexception error.
mabye its because the url download a .txt file instead of showing the data, as u can see:
https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&dt=t&q=olas
this is the code i used:
URL url = new URL(urlstring);
HttpURLConnection httpURLconnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLconnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
Just add user agent to your httpURLconnection.
HttpURLConnection httpURLconnection = (HttpURLConnection) url.openConnection();
httpURLconnection.setRequestProperty("User-Agent","MyAppName/1.0");
String uri = "http://maps.google.com/maps?saddr=" + strlat + "," + strlon + "&daddr=" + strDlat + "," + strDlon;
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
intent.setComponent((new ComponentName("com.google.android.apps.maps",
"com.google.android.maps.MapsActivity")));
startActivity(intent);
This code opens a google map and We can navigate to the destination address without any problem.
My Question is if the destination address also keeps changing (say user 2 is moving to another location and I have the location) how can we update that on google map?
Is there any way to inform google map that please update the destination location too.
I don't want to add google map in my activity.
Please help me out.
No, you can't inform Google Maps about location changes. It will automatically track user location.
However, you can only pass one location (e.g. destination) and let user decide what to do with it.
We cannot update the google map started by the following code
String uri = "http://maps.google.com/maps?saddr=" + strlat + "," + strlon + "&daddr=" + strDlat + "," + strDlon;
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
intent.setComponent((new ComponentName("com.google.android.apps.maps",
"com.google.android.maps.MapsActivity")));
startActivity(intent);`
I have acheived this task by
1. create GoogleMapActivity with a map
2. draw markers two markers on it with lat,long
3. get dirctions
using following code
`
private String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
Log.i("MAP", "url="+url);
return url;
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();;
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(10000);
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
`
then draw the lines on google map
I have an Android app that sends a http post to a remote server:
protected Void doInBackground(Void... params) {
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MapsActivity.EXTRA_MESSAGE);
double longitude = intent.getDoubleExtra(MapsActivity.EXTRA_LONGITUDE, 0.0);
double latitude = intent.getDoubleExtra(MapsActivity.EXTRA_LATITUDE, 0.0);
Log.d("doInBackground", message);
Log.d("doInBackground", String.valueOf(longitude));
Log.d("doInBackground", String.valueOf(latitude));
URL url = null;
HttpURLConnection client = null;
try {
// Establish http connection
url = new URL("http://******.com/");
client = (HttpURLConnection) url.openConnection();
client.setDoOutput(true);
client.setDoInput(true);
client.setRequestMethod("POST");
client.connect();
OutputStreamWriter writer = new OutputStreamWriter(client.getOutputStream());
String output;
output = URLEncoder.encode("message", "UTF-8")
+ "=" + URLEncoder.encode(message, "UTF-8");
output += "&" + URLEncoder.encode("longitude", "UTF-8") + "="
+ URLEncoder.encode(String.valueOf(longitude), "UTF-8");
output += "&" + URLEncoder.encode("latitude", "UTF-8") + "="
+ URLEncoder.encode(String.valueOf(latitude), "UTF-8");
Log.d("doInBackground(output)", output);
Log.d("doInBackground(code)", String.valueOf(client.getResponseCode())); // Return 200
writer.write(output);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
client.disconnect();
}
return null;
}
In the server, I have:
<?php
$m = urldecode($_POST['message']);
$long = urldecode($_POST['longitude']);
$lat = urldecode($_POST['latitude']);
print " ==== POST DATA =====
Message : $m
Longitude : $long
Latitude : $lat";
?>
client.getResponseCode() returns 200, I think that means my connection was successful? But the website still shows nothing. What might cause the problem?
I got
E/GMPM: getGoogleAppId failed with status: 10
E/GMPM: Uploading is not possible. App measurement disabled
might this be the problem?
What do you mean by the website doesn't show anything? You cannot see the print when you reload the web site because you are not saving it anywhere, you are simply printing out the values on that one single request. To debug you can write the post params to a file instead to see if they are coming through or better yet log the returned object on the android side.
I am writing below code to get json string from url and parse json string to get stock info in an android app. My code is given below:
url = new URL(in);
Log.e(STOCK,"comes here ..0 ");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream stream = conn.getInputStream();
String dataone = convertStreamToString(stream);
reader = new JSONObject(dataone);
Log.e(STOCK,"comes here ..1 ");
JSONObject data = reader.getJSONObject("data");
previousClose = data.getString("previousClose");
lastPrice = data.getString("lastPrice");
low52 = data.getString("low52");
totalTradedValue = data.getString("totalTradedValue");
Toast.makeText(MainActivity.this,lastPrice,Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this,totalTradedValue,Toast.LENGTH_LONG).show();
But I am getting exception after opening url, I have added internet permission in Android Manifest xml.
I currently have a mediaplayer and am trying to get the redirect address from my source path. Since the media player does not support redirect handling, I am trying to get the redirected url path by creating a httpurlconnection etc. However, I'm not sure if I am doing it right. Any help would be appreciated. Thanks.
Code:
Log.d(TAG, "create url - test");
URL testUrl = new URL(path);
HttpURLConnection conn = (HttpURLConnection)testUrl.openConnection();
String test = conn.getURL().toString();
String test1 = conn.getHeaderField(2);
String test2 = conn.toString();
Log.d(TAG, "normal stuff test is: " + test);
Log.d(TAG, "header field test is: " + test1);
Log.d(TAG, "url to string is: " + test2);
The code below follows one hop of URL redirects. By using a HTTP HEAD request rather than GET it consumes radically less bandwith. It should be fairly straight forward to extend this method to handle multiple hops.
public URI followRedirects(URI original) throws ClientProtocolException, IOException, URISyntaxException
{
HttpHead headRequest = new HttpHead(original);
HttpResponse response = client.execute(headRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||
statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
{
String location = response.getHeaders("Location")[0].toString();
String redirecturl = location.replace("Location: ", "");
return new URI(redirecturl);
}
return original;
}
It assumes you have already set up an HttpClient stored in the field client.
Also see this question.