Using HTTP Get request to overcome the Geocoder limits in Android - java

Is it possible to use HTTP API and perform HTTP Get request for Google maps in order to overcome the limits of using Geocoder API when requesting latitude and longitude of places?
Something like-
URL url = new URL("https://www.google.com/maps/place/Paris/");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
System.out.println("Value" + connection.getResponseCode());
System.out.println(connection.getResponseMessage());
System.out.println("content"+connection.getContent());
or
URL url = new URL("https://www.google.com/maps/place/Paris/");
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
String strTemp = "";
while (null != (strTemp = br.readLine())) {
System.out.println(strTemp);
}
Expecting the response to contain the lat and long of the place as in Google maps site, that way my client appears as a regular web client of google maps.

The Places API request has quota limit too, you can see the detail in this page: https://developers.google.com/places/webservice/usage
Also, you need an API key to do your Places API request, a sample way to do a Places API URL request in Android should be like this:
URL placeUrl = new URL("https://maps.googleapis.com/maps/api/place/textsearch/json?query=restaurants+in+Sydney&key=AddYourOwnKeyHere");
HttpURLConnection connection = (HttpURLConnection)placeUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = null;
InputStream inputStream = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
Log.d(TAG, buffer.toString());
}
else {
Log.i(TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
You should do this URL request in background thread, for example, in the doInBackground() method of AsyncTask.
You can also visit this tutorial for more detail about how to use Places API in Android.

Related

Scrape posts on Imgur using HttpURLConnection

I want to scrape posts from Imgur.
Let's say we have this link(permalink): https://imgur.com/gallery/ZXjNfqu/comment/1717354251
I want to load this url via HttpURLConnection and read some data from content(HTML).
I have this code:
try{
//create connection
HttpURLConnection connection = (HttpURLConnection)(new URL(url)).openConnection();
connection.setRequestMethod("GET");
//get response
int responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
//read html
StringBuilder body = new StringBuilder();
try(var reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))){
String line;
while((line = reader.readLine()) != null){
body.append(line);
}
}
//print html
System.out.println(body.toString());
}else{
//read error content
StringBuilder body = new StringBuilder();
try(var reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))){
String line;
while((line = reader.readLine()) != null){
body.append(line);
}
}
String bodyStr = body.toString().trim();
throw new Exception("Bad HTTP Request: " + responseCode +
" - " + connection.getResponseMessage() +
(bodyStr.isEmpty() ? "" : " - " + bodyStr));
}
}catch(Exception e){ e.printStackTrace(); }
Via HttpURLConnection I get only a part of the real page(what I see in browser). From HTML is missing at least image url and comments.
How I can get all content via HttpURLConnection?
P.S.: Is not necessary to use HttpURLConnection
Edit 1: I think it's because of javascript. But I'm not sure.

POST in JAVA using HttpURLConnection getting a HTTP response code 400

I'm pretty new to making HTTP connections and working with API's in Java, so I'm not sure where the problem lies. When I send out a POST connection request in order to send a JSON formatted String of text to the other side, I get an error back along with a 400 response code. When I look up that code, it seems my connection isn't properly formatted. Code is below, along with the error message. Please help! Thanks!
public void sendToAPI(String urlPass, String param) throws IOException {
URL url = new URL(urlPass);
HttpURLConnection connectionOut = (HttpURLConnection) url.openConnection();
connectionOut.setRequestMethod("POST");
connectionOut.setConnectTimeout(5000);
connectionOut.setReadTimeout(5000);
connectionOut.setRequestProperty("Content-Type", "application/json");
connectionOut.setRequestProperty("Content-Length", Integer.toString(param.length()));
connectionOut.setDoOutput(true);
connectionOut.setDoInput(true);
connectionOut.connect();
DataOutputStream stream = new DataOutputStream(connectionOut.getOutputStream());
stream.writeUTF(param);
stream.flush();
stream.close();
int responsecode = connectionOut.getResponseCode();
if(responsecode != 200) {
System.out.println("Response Code is " + responsecode);
}
BufferedReader in = new BufferedReader(
new InputStreamReader(connectionOut.getInputStream()));
String output;
StringBuffer response = new StringBuffer();
while ((output = in.readLine()) != null) {
response.append(output);
}
in.close();
//printing result from response
System.out.println(response.toString());
}
Response Code is 400
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL:XXX
u can try this code:
InputStream inputStream;
if (responseCode == 200) {
inputStream = con.getInputStream();
} else {
inputStream = con.getErrorStream();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String lines;
while ((lines = reader.readLine()) != null) {
builder.append(lines);
builder.append(System.getProperty("line.separator"));
}
String retStr = builder.toString().trim();
reader.close();
System.out.println("retStr: " + retStr);
So after playing around with the DataOutputStream, I replaced the below code:
DataOutputStream stream = new DataOutputStream(connectionOut.getOutputStream());
stream.writeUTF(param);
With another example I found online:
OutputStream os = connectionOut.getOutputStream();
os.write(param.getBytes());
os.flush();
os.close();
I'm not sure yet why, but this suddenly got the proper response code I was looking for, so the format it was sent in matched what they requested. Thanks for all responses.

Can Facebook return a https status code different than 200 when requesting user info is successful?

I have created a code that checks if user is logged into Facebook. This is how it looks like:
URL url = new URL("https://graph.facebook.com/me?access_token=" + this.fb_token);
System.out.println("Attempting to open connection");
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
int responseCode = conn.getResponseCode();
System.out.println(responseCode);
BufferedReader reader;
if(responseCode != 200) {
reader = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
}
else{
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
}
String json = reader.readLine();
reader.close();
conn.disconnect();
return json;
Next, I parse the Json, check if it's en error or data code and log the user.
My question is: Is if(responseCode != 200) check enough? Can Facebook return a different status code in case of successful authentication?

How i can get connected with qc 12 with rest api

Can u please help me to understand with simple piece of java code to get connect wth qc 12 using rest api.
I gone thorough the rest api documentation but am not clear with how to start with.but it will be helpful if people can show me a simple java code for authentication(login,logout or getting defect details) using rest api. Also want to know do i need to include any jars in my build path.
Thanks a lot friends.
I don't quite get what you're asking, but if you want to connect to a REST API, there are several ways... I usually use HttpURLConnection, here's an example of a get:
public String getProfile(String URL) throws IOException {
URL getURL = new URL(url);
//Establish a https connection with that URL.
HttpURLConnection con = (HttpURLConnection) getURL.openConnection();
//Select the request method, in this case GET.
con.setRequestMethod("GET");
//Add the request headers.
con.setRequestProperty("header", headerValue);
System.out.println("\nSending 'GET' request to URL : " + url);
int responseCode;
try {
responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
} catch (Exception e) {
System.out.println("Error: Connection problem.");
}
InputStreamReader isr = new InputStreamReader(con.getInputStream());
BufferedReader br = new BufferedReader(isr);
StringBuffer response = new StringBuffer();
String inputLine;
while ((inputLine = br.readLine()) != null) {
//Save the response.
response.append(inputLine + '\n');
}
br.close();
return response.toString();
}

how to make http get request in Android

I am new to android.So i can any one sho me how to make a http get request such as
GET /photos?size=original&file=vacation.jpg HTTP/1.1
Host: photos.example.net:80
Authorization: OAuth realm="http://photos.example.net/photos",
oauth_consumer_key="dpf43f3p2l4k3l03",
oauth_token="nnch734d00sl2jdk",
oauth_nonce="kllo9940pd9333jh",
oauth_timestamp="1191242096",
oauth_signature_method="HMAC-SHA1",
oauth_version="1.0",
oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D"
in android(java)?
You're gonna want to get familiar with InputStreams and OutputStreams in Android, if you've done this in regular java before then its essentially the same thing. You need to open a connection with the request property as "GET", you then write your parameters to the output stream and read the response through an input stream. You can see this in my code below:
try {
URL url = null;
String response = null;
String parameters = "param1=value1&param2=value2";
url = new URL("http://www.somedomain.com/sendGetData.php");
//create the connection
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
//set the request method to GET
connection.setRequestMethod("GET");
//get the output stream from the connection you created
request = new OutputStreamWriter(connection.getOutputStream());
//write your data to the ouputstream
request.write(parameters);
request.flush();
request.close();
String line = "";
//create your inputsream
InputStreamReader isr = new InputStreamReader(
connection.getInputStream());
//read in the data from input stream, this can be done a variety of ways
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
//get the string version of the response data
response = sb.toString();
//do what you want with the data now
//always remember to close your input and output streams
isr.close();
reader.close();
} catch (IOException e) {
Log.e("HTTP GET:", e.toString());
}

Categories