HttpsURLConnection + Cloudflare API FileNotFoundException - java

I'm trying to create an app for android and I'm trying to read my stats from my CloudFlare Dashboard.
The strange thing is that if my code reaches the line ins = con != null ? con.getInputStream() : null; It will say "FileNotFoundException".
The headers are set as they should. Here is the quote from the CF API Documentation:
The dashboard view provides both totals and timeseries data for the given zone and time period across the entire CloudFlare network.
GET /zones/:zone_identifier/analytics/dashboard
- https://api.cloudflare.com/#zone-analytics-dashboard
Some parameters are optional, I double checked my data already and it works fine in Postman.
I tried to use http but CF doesn't allow it.
My code:
class JsonRequest extends AsyncTask<String, String, String> {
private String readStream(InputStream is) {
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while (i != -1) {
bo.write(i);
i = is.read();
}
return bo.toString();
} catch (IOException e) {
return "";
}
}
protected String doInBackground(String... params) {
URL myurl = null;
try {
myurl = new URL(params[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
HttpsURLConnection con = null;
try {
con = (HttpsURLConnection)myurl.openConnection();
con.setRequestProperty("X-Auth-Email", "email");
con.setRequestProperty("X-Auth-Key", "key");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("User-Agent","Mozilla/5.0 ( compatible ) ");
con.setRequestProperty("Accept","*/*");
con.setDoOutput(false);
} catch (IOException e) {
e.printStackTrace();
}
InputStream ins = null;
try {
ins = con != null ? con.getInputStream() : null; // FileNotFoundException
} catch (IOException e) {
e.printStackTrace();
}
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return readStream(ins);
}
}

Related

Aplication with json-simple crash after non json data

Ive got
HttpURLConnection urlConnection = null;
String result = "";
try {
String host = "http://www.example.com/json.json";
URL url = new URL(host);
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
if(code==200){
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
if (in != null) {
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject)jsonParser.parse(new InputStreamReader(in, "UTF-8"));
result=(String) jsonObject.get("name");
System.out.print(jsonObject);
}
in.close();
} else { result="9";}
return result;
} catch (MalformedURLException e) {
result="9";
} catch (IOException e) {
result="9";
}
catch (ParseException e) {
e.printStackTrace();
result="9";
}
finally {
urlConnection.disconnect();
}
return result;
When i input valid json data, all is OK, but if i got non json data, i got aplication crash with :
Caused by: java.lang.ClassCastException: java.lang.Long cannot be cast to org.json.simple.JSONObject
I think that
catch (ParseException e) {
e.printStackTrace();
result="9";
}
should handle this, but no.
So what i must do to avoid situation that aplication will crash when i do not get valid json?
The thrown exception is a ClassCastException. Maybe you can catch that exception also by adding another catch?
catch (ClassCastException e) {
e.printStackTrace();
result="9";
}
Try this to make a http request
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
URL myUrl = null;
HttpURLConnection conn = null;
String response = "";
//String data = params[0];
try {
myUrl = new URL("http://www.example.com/json.json");
conn = (HttpURLConnection) myUrl.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
//one long string, first encode is the key to get the data on your web
//page, second encode is the value, keep concatenating key and value.
//theres another ways which easier then this long string in case you are
//posting a lot of info, look it up.
String postData = URLEncoder.encode("key", "UTF-8") + "=" +
URLEncoder.encode("value", "UTF-8");
OutputStream os = conn.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
bufferedWriter.write(postData);
bufferedWriter.flush();
bufferedWriter.close();
InputStream inputStream = conn.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
inputStream.close();
conn.disconnect();
os.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
} catch (JSONException e) {
//s may not be json
}
}
}
Before getting String from Json Object, check whether the Json object is not null and has that string. and then try to get it.
if (jsonObject!=null && jsonObject.has("name"))
{
result = jsonObject.get("name");
System.out.print(result);
}

Trouble with "inputstream" when creating mobile app that downloads weather information (with AsyncTask)

I'm trying to make a mobile app that downloads info from the openweathermap.org apis. For example, if you feed that app this link: http://api.openweathermap.org/data/2.5/weather?q=Boston,us&appid=fed33a8f8fd54814d7cbe8515a5c25d7 you will get the information about the weather in Boston, MA. My code seems to work up to the point where I have to convert the input stream to a string variable. When I do that, I get garbage. Is there a particular way to do this seemingly simple task in a proper way? Here is my code so far...
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0]);
} catch (IOException e) {
return null;
}
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
TextView test = (TextView) findViewById(R.id.test);
if(result!=null) test.setText(result);
else{
Log.i(DEBUG_TAG, "returned result is null");}
}
}
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.i(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
String text = getStringFromInputStream(is);
//JSONObject json = new JSONObject(text);
//try (Scanner scanner = new Scanner(is, StandardCharsets.UTF_8.name())) {
//text = scanner.useDelimiter("\\A").next();
//}
//Bitmap bitmap = BitmapFactory.decodeStream(is);
return text;
}catch(Exception e) {
Log.i(DEBUG_TAG, e.toString());
}finally {
if (is != null) {
is.close();
}
}
return null;
}
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
Check this library . Is An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries.

How can i count how much data have already sent to server by HttpURLConnection?

I sent a byte[] to server. I can count byte[] size which i am going to send, but how can i get size of byte[] which have already sent? I want implement it in order to show to user a progressBar in % .
Here is the my code :
public static JSONObject sentJsonToServer(final URL url, final byte[] data, final String newValue) {
ExecutorService ex = Executors.newCachedThreadPool();
Future<JSONObject> objectFuture = ex.submit(new Callable<JSONObject>() {
#Override
public JSONObject call() throws Exception {
BufferedOutputStream bos = null;
HttpURLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Content-Type", newValue);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
bos = new BufferedOutputStream(urlConnection.getOutputStream());
bos.write(data);
bos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
// returns POST request
if (urlConnection != null) {
return getJSONFromUrl(urlConnection);
} else {
throw new NullPointerException();
}
}
});
JSONObject responseJson = null;
try {
responseJson = objectFuture.get();
} catch (InterruptedException | ExecutionException | NullPointerException e) {
e.printStackTrace();
}
System.out.println("LAST JSOOOOOOOOOOON!!!!!!!!!!!!!!! " + responseJson);
return responseJson;
}
I try implement smth like ProgressListener() but without succes(
How i can make it?

How to read string from php to android studio (java)

I don't know why i get a null value when i call the GetPHPData() function. The "out" variable returns nothing (""). I make a Toast.makeTest and it returns empty string. Please help. This is my code:
public class PHPConnect extends Activity
{
String url = "http://122.2.8.226/MITBookstore/sqlconnect.php";
HttpURLConnection urlConnection = null;
String out = null;
public String GetPHPData()
{
try {
urlConnection = (HttpURLConnection) new URL(url).openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(10000);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
out = readStream(in);
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
finally
{
urlConnection.disconnect();
return out;
}
}
private String readStream(BufferedReader is)
{
try
{
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while(i != -1)
{
bo.write(i);
i = is.read();
}
return bo.toString();
} catch (IOException e)
{
return e.getMessage();
}
}
}
By the way, im running a wamp server and I port forwarded my router, on local host, the url works, but on remote connection, it won't return a string. You can try out the url, the result is: "This is the output:emil"
Can you please try below piece of code which is working for me, also add INTERNET permission in android manifest file. Still if it is not working then may be issue with server end then try to debug it.
URL url;
try {
url = new URL("myurl");
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Unable to do HTTP POST from J2ME (Nokia S40 6thEdition)

Im unable to do HTTP POST using J2ME below is the code that im using which is throwing an exception when I try and write to the OutputStrem.
In the code Below SYSO prints "here5". Please need some guidance. Basically I've put the http connection part in a separate threads run method, to keep it aloof from the UI thread.
public void run(){
HttpConnection http = null;
OutputStream out = null;
String msg = "lat=10&long=20&mac=923873";
try{
String url = "http://xxxx.php";
byte[] data = null;
InputStream istrm = null;
http = (HttpConnection)Connector.open(url);
}
catch(Exception e)
{
System.out.println("here1");
}
try
{
http.setRequestMethod(HttpConnection.POST);
}
catch(Exception e)
{
System.out.println("here2");
}
try{
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setRequestProperty("User-Agent", "HttpMidlet/0.2");
http.setRequestProperty("Custom-Property", "MyCustomProperty/1.0; AnotherProperty/debug_0.1");
http.setRequestProperty("Content-Length", ""+msg.getBytes().length);
}
catch(Exception e)
{
System.out.println("here3");
}
try{
out = http.openOutputStream();
}
catch(Exception e)
{
System.out.println("here4");
}
try{
out.write(msg.getBytes());
out.flush();
}
catch(Exception e)
{
System.out.println("here5");
}
}
/**
* Send the data to the URL of Server Site using the POST connection.
*
* #return the response of server.
* #throws Exception
*/
public byte[] send() throws Exception {
HttpConnection hc = null;
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] res = null;
try {
hc = (HttpConnection) Connector.open(url);
hc.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + getBoundaryString());
hc.setRequestMethod(HttpConnection.POST);
OutputStream dout = hc.openOutputStream();
dout.write(postBytes);
if (dout!=null) {
dout.close();
dout = null;
}
int ch;
is = hc.openInputStream();
while ((ch = is.read()) != -1) {
bos.write(ch);
}
res = bos.toByteArray();
} catch (Exception e) {
// if an error occurred connecting to the server.
throw new Exception(e.getMessage());
} finally {
try {
if (bos != null)
bos.close();
if (is != null)
is.close();
if (hc != null)
hc.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return res;
}
According to this Nokia Sample you do not need to call setRequestProperty methods. Another interesting point is the usage of Connector.open(urlstring, Connector.READ_WRITE).
I resolved this by re-installing the emulator.

Categories