Get live quote from web url - android

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.

Related

Read Downloaded Text File - Android - error - FileNotFoundException

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");

Maximum HttpUrlConnection Response

I am using HttpUrlConnection to get JSON strings from web, but the response is good for smaller strings but not for larger ones: this is what I am seeing in my app, and this is the data from server to a web page I did not include any HTML from server side.
Here is my code:
URL adr = new URL("http://placeform.tk/forapp.php");
HttpURLConnection connection =(HttpURLConnection) adr.openConnection();
connection.connect();
int rcode = connection.getResponseCode();
Log.d("rcode",Integer.toString(rcode));
if (rcode == HttpURLConnection.HTTP_OK) {
InputStream inputStreamReader = connection.getInputStream();
String c = connection.getHeaderField("content-length");
Reader rd = new InputStreamReader(inputStreamReader);
Log.d("contentsize", Integer.toString(connection.getContentLength()) + c);
chars = new char[connection.getContentLength()];
Log.d("contentsize", Integer.toString((int)connection.getContentLength()) + c);
rd.read(chars);
String output = new String(chars);
use this link and add that class in your project and call webservice from that class. cause that class will build up your response string with use of string builder. have a look at that class. and comment if you have any problem.

how can send a json frame to mysever hear i can reserve a json and i wnd send the data

I posted the code I used for reading the data from my server but I don't know how to send a json frame to the server.
I want to send the data string.
try {
URL url = new URL(params[0]);
con = (HttpURLConnection)url.openConnection();
con.connect();
InputStream in = con.getInputStream();
red = new BufferedReader(new InputStreamReader(in));
String line = "";
buffer = new StringBuffer();
while ((line=red.readLine())!= null){
buffer.append(line);
}
return buffer.toString();
I would assume that you are trying to post some JSON Object to a URL,
While using HttpURLConnection for connection you can set to its instance that this is a POST header request, if you are indeed posting something on that URL.
After that you can use DataOutputStream instance to write(POST) your JSON data something like this.
I have written a snippet which you can check, the code is also available on Github
private class MyTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
/**
* Kindly change this url string with your own, where you want to post your json data
*/
URL url = new URL("");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
// when you are posting do make sure you assign appropriate header
// In this case POST.
httpURLConnection.setRequestMethod("POST");
httpURLConnection.connect();
// like this you can create your JOSN object which you want to send
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("email", "dddd#gmail.com"); //dummy data
jsonObject.addProperty("password", "password");// dummy data
// And this is how you will write to the URL
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();
Log.d("TAG", "" + IOUtils.toString(httpURLConnection.getInputStream()));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
This code uses apache-common-io, to get the String from the input stream, if you would like you can change that.

Error on using googmaps api

Im getting the following error on trying to use an web service from google api maps:
{
"error_message" : "Requests to this API must be over SSL.",
"results" : [],
"status" : "REQUEST_DENIED"
}
the url used to invoke the web service:
http://maps.googleapis.com/maps/api/geocode/json?key=my_key=Rua+Vergueiro,+1883,+S%C3%A3o+Paulo,+Brazil&sensor=true
method used to call the web service:
enter code here
public static String httpPost(String urlStr) throws Exception {
String novaUrl = urlStr.trim();
novaUrl = urlStr.replaceAll(" ", "+");
novaUrl = novaUrl.replaceAll("\r", "");
novaUrl = novaUrl.replaceAll("\t", "");
novaUrl = novaUrl.replaceAll("\n", "");
URL url = new URL(novaUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urldecoded");
// Create the form content
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.close();
out.close();
// Buffer the result into a string
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
Spanned retorno = Html.fromHtml(sb.toString());
return retorno.toString();
}
How to solve this problem?
Thanks.
Try using this URL. Error just because of http and https. https is used for secure line.
https://maps.googleapis.com/maps/api/geocode/json?key=my_key=Rua+Vergueiro,+1883,+S%C3%A3o+Paulo,+Brazil&sensor=true
Now when you click on this you will get some error like this .. The provided API key is invalid.
For that just provide correct API key that you retrieved from Google Console.
Your given URL :: https://maps.googleapis.com/maps/api/geocode/json?key=my_key=Rua+Vergueiro,+1883,+S%C3%A3o+Paulo,+Brazil&sensor=true
here key=my_key Here is the problem, please provide correct API key and you problem will be solved.

InputStream returns 0 with HttpUrlConnection in Android

I'm doing a HttpUrlConnection in Android application with an URL. The URL is giving me response in the browser but in the code below InputStream response is 0. Why?
Here's my code:
URL url = new URL("https://certify.securenet.com/payment.scrnt");
HttpURLConnection httpCon = (HttpURLConnection)url.openConnection();
InputStream in = httpCon.getInputStream();
byte content[] = new byte[in.available()];
in.read(content, 0, content.length);
String receivedString = new String(content);
Log.d("Received String", receivedString)
Try changing from "https://" to "http://" in the URL if you don't need a secure connection.
Or try changing to HttpsUrlconnection instead of HttpUrlconnection.
I suppose that you have to use HttpsUrlConnection for URLs with https scheme.

Categories

Resources