I think i did something wrong with string named "url", but im not sure what should i change, what am i doing wrong?
I didn't want to share my api key, normally it is there.
I use no commercial version of flickr.
Main activity:
FlickrFetchr flickrFetchr = new FlickrFetchr();
Log.d("HTTP_JSON",flickrFetchr.getJSONString());
JsonString is always "sth went wrong"
FlickrFetchr class:
public class FlickrFetchr {
String API_KEY = "MY_API";
HttpsURLConnection connection;
public byte[] getUrlBytes(String urlSpec)
{
try {
URL url = new URL(urlSpec);
connection = (HttpsURLConnection) url.openConnection();
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream imput = connection.getInputStream();
if(connection.getResponseCode() != HttpsURLConnection.HTTP_OK) {
throw new Exception();
}
int bytesRead;
byte [] buffer = new byte[1024] ;
do {
bytesRead = imput.read(buffer);
out.write(buffer,0,bytesRead);
}while (imput.read(buffer)>0);
out.close();
return out.toByteArray();
}catch (Exception e) {
Log.e("HTTPeerpr", e.getMessage());
byte[] emptyArray = new byte[0];
return emptyArray;
}
finally {
connection.disconnect();
}
}
public String getURLString(String urlSpec)
{
return getUrlBytes(urlSpec).toString();
}
public String getJSONString()
{
String jsonString = "sth went wrong";
try {
String url = Uri.parse("https://api.flickr.com/services/rest/")
.buildUpon()
.appendQueryParameter("method", "flickr.photos.getRecent")
.appendQueryParameter("api key", API_KEY)
.appendQueryParameter("format", "json")
.appendQueryParameter("nojsoncallback", "1")
.appendQueryParameter("extras", "url_s")
.build().toString();
jsonString = getURLString(url);
}catch (Exception je)
{
Log.e("JSON_ERROR", je.getMessage());
}
return jsonString;
}
}
Thanks for your help.
Related
Currently i am fetching a package details(Onnet Minutes, Offnet Minutes, etc) from a Json file "Data.json" from assets but i know we cannot change values from assets. So my Question is how to copy Data.json to internal storage and then Load it for read/Write.
I am using this to load Data.Json from Assets
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("Data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
Toast.makeText(jazz_sim_lagao_offer_details.this, "JSON Loaded", Toast.LENGTH_SHORT).show();
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
and using this code to update data
private void UpdateData() {
JSONObject JSONobj = null;
try {
loadJSONFromAsset();
//get JSONObject from JSON file
JSONobj = new JSONObject(loadJSONFromAsset());
//fetch JSONObject named
JSONObject Jazz_SimLagaoOffer = JSONobj.getJSONObject("packages").getJSONObject("jazz_packages").getJSONObject("call_packages").getJSONObject("sim_lagao_offer");
String Jazz_SimLagaoOffer_ONNET = Jazz_SimLagaoOffer.getString("onnet");
Jazz_SimLagaoOffer_OnNet_TextView.setText(Jazz_SimLagaoOffer_ONNET);
String Jazz_SimLagaoOffer_OFFNET = Jazz_SimLagaoOffer.getString("offnet");
Jazz_SimLagaoOffer_OffNet_TextView.setText(Jazz_SimLagaoOffer_OFFNET);
String Jazz_SimLagaoOffer_MBs = Jazz_SimLagaoOffer.getString("mbs");
Jazz_SimLagaoOffer_Mb_TextView.setText(Jazz_SimLagaoOffer_MBs);
String Jazz_SimLagaoOffer_SMS = Jazz_SimLagaoOffer.getString("sms");
Jazz_SimLagaoOffer_Sms_TextView.setText(Jazz_SimLagaoOffer_SMS);
String Jazz_SimLagaoOffer_SUBCODE = Jazz_SimLagaoOffer.getString("sub_code");
Jazz_SimLagaoOffer_Sub_Code_TextView.setText(Jazz_SimLagaoOffer_SUBCODE);
String Jazz_SimLagaoOffer_CHECKCODE = Jazz_SimLagaoOffer.getString("check_code");
Jazz_SimLagaoOffer_Check_Code_TextView.setText(Jazz_SimLagaoOffer_CHECKCODE);
String Jazz_SimLagaoOffer_UNSUBCODE = Jazz_SimLagaoOffer.getString("unsub_code");
Jazz_SimLagaoOffer_Unsub_Code_TextView.setText(Jazz_SimLagaoOffer_UNSUBCODE);
Jazz_SimLagaoOffer_Charges = Jazz_SimLagaoOffer.getString("charges");
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), JSONobj + "", Toast.LENGTH_SHORT).show();
}
}
How to Get Json Object?
Here is My Data.Json
{
"packages" : {
"jazz_packages" : {
"call_packages" : {
"sim_lagao_offer" : {
"charges" : "0.01",
"check_code" : "*551*2#",
"mbs" : "1500",
"offnet" : "5000",
"onnet" : "3000",
"sms" : "3000",
"sub_code" : "*551#",
"unsub_code" : "*551*3#"
}
}
}
}
}
Try this
private void CopyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
System.out.println("File name => "+filename);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(YOUR_ASSETS_FILE); // if files resides inside the "Files" directory itself
out = new FileOutputStream(STORAGE_PATH).toString() +"/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
e.printStackTrace();
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Use below code to read from storage
String jsongString = readFromFile();
JSONObject mainJsonObject = new JSONObject(jsongString);
JSONObject Jazz_SimLagaoOffer = mainJsonObject.getJSONObject("packages").getJSONObject("jazz_packages").getJSONObject("call_packages").getJSONObject("sim_lagao_offer");
Use below method to read data from internal storage file and return as String.
private String readFromFile() {
String ret = "";
InputStream inputStream = null;
try {
inputStream = openFileInput("names.json");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
Hope this work :)
I Got Answer my own Question after 1 Day Research and Thanks to #pratik vekariya
helped me a lot.
CopyAssets() works perfect as defined #pratik vekariya in his answer and to readfromfile see my Question loadJSONFromAssets()
and i Just replaced line
InputStream is = getAssets().open("Data.json");
with this
InputStream is = new FileInputStream(getFilesDir().toString() +"/" + "Data.json");
to to load .json file from files and get json object from inputStrem
When I'm trying to download html using this method:
public class DownloadHtml extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection connection = null;
try {
url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
char currentChar = (char) data;
result += currentChar;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return "Failed";
}
}
}
And logging a result
DownloadHtml downloadHtml = new DownloadHtml();
String result = null;
try {
result = downloadHtml.execute("http://stackoverflow.com").get();
} catch (Exception e) {
e.printStackTrace();
}
Log.i("Html", result);
I am gettin only small part of it.
Is there a way to get whole HTML of webpage?
Solution was simple. Looks like Log.i doesn't print everything in one go.
When I have tried to get all the links from HTML they were successfully printed.
I am new to android.The Image is store in server by Base64 format. so how can i get it from server to My Project and set to my ImageView using Json Object.
Please Help me
Any help will be Appappreciated
Try this:
Convert Url to byte[] first:
byte[] bitmapdata = getByteArrayImage(url);
Method:
private byte[] getByteArrayImage(String url){
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
return baf.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
Now convert the byte[] to bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata , 0, bitmapdata .length);
And set your bitmap to your ImageView:
img= (ImageView) findViewById(R.id.imgView);
img.setImageBitmap(bitmap );
I found easy solution:
byte[] img = Base64.decode(userHeader.GetImage(), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(img, 0, img.length);
imageww.setImageBitmap(getCircleBitmap(bitmap));
Using Apache's commons-io-2.5 lib we can get using this function IOUtils.toByteArray(is)
public static String getByteArrayFromURL(final String url) {
String base64Image = "";
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> result = executor.submit(new Callable<String>() {
public String call() throws Exception {
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
return Base64.encodeToString(IOUtils.toByteArray(is), Base64.NO_WRAP);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
});
try {
base64Image = result.get();
} catch (Exception exception) {
exception.printStackTrace();
}
return base64Image;
}
We are getting some very weird behavior in Android. Our network stack (that talks to a REST server) works fine in almost all situations, except when we do a GET shortly after doing a larger POST. What appears to be happening is that the Output stream is not flushing, and ends up sending the last line that was in there when the new socket is opened. Please note, each connection is a new object created, so this is unexpected behavior. First, the error code that seems to point me to the output stream, these are from the server logs.
10.1.8.195 - - [07/Nov/2012:13:36:28 -0700] "POST /iou/lender HTTP/1.1" 200 28 "-" "Android"
10.1.8.195 - - [07/Nov/2012:13:36:36 -0700] "------------V2ymHFg03ehbqgZCaKO6jy" 400 173 "-" "-"
That attempt after should be a GET that then pulls the data from the server that includes the new entry added via the POST. However, all we get is again what appears to be the last line from the output stream from the POST. Here is our core code for the network stack, if more of the surrounding code is needed, let me know.
public Object serverConnect(String url, String method,
Hashtable<String, Object> params) {
HttpConnection c = null;
InputStream is = null;
OutputStream out = null;
ByteArrayOutputStream postDataByteArrayImage = new ByteArrayOutputStream();
byte[] data;
String boundry = "----------V2ymHFg03ehbqgZCaKO6jy";
try {
if (!url.startsWith("/")) {
url = "/" + url;
}
String uri = Control.URL_Secure + Control.dtserver + ":"
+ Control.port + url;
ByteArrayOutputStream postDataByteArray = new ByteArrayOutputStream();
params.put("sessionId", Control.sessionId);
if (method.equals("GET")) {
uri = uri + "?";
Enumeration enumParams = params.keys();
while (enumParams.hasMoreElements()) {
if (!uri.endsWith("?")) {
uri = uri + "&";
}
String key = (String) enumParams.nextElement();
uri = uri
+ key
+ "="
+ java.net.URLEncoder.encode((String) params
.get(key));
}
} else if (method.equals("POST")) {
Enumeration enumParams = params.keys();
postDataByteArray.write(("--").getBytes());
postDataByteArray.write((boundry).getBytes());
postDataByteArray.write(("\r\n").getBytes());
while (enumParams.hasMoreElements()) {
String key = (String) enumParams.nextElement();
if (!key.equals("image")){
postDataByteArray
.write(("Content-Disposition: form-data; name=\"")
.getBytes());
postDataByteArray.write((key).getBytes());
postDataByteArray.write(("\"").getBytes());
postDataByteArray.write(("\r\n\r\n").getBytes());
postDataByteArray.write(((String) params.get(key))
.getBytes());
postDataByteArray.write(("\r\n").getBytes());
postDataByteArray.write(("--").getBytes());
postDataByteArray.write(boundry.getBytes());
postDataByteArray.write(("\r\n").getBytes());
}
}
postDataByteArray.close();
}
Log.i("URL", uri);
URL urltoConenct = new URL(uri);
URLConnection connection = urltoConenct.openConnection();
HttpURLConnection urlConnection = (HttpURLConnection) connection;
URLConnection.setDefaultRequestProperty("Method", method); // default
urlConnection.setRequestProperty("User-Agent", "Android");
if (method.equals("POST")) {
urlConnection.setDoOutput(true);
urlConnection.setFixedLengthStreamingMode(postDataByteArray.toByteArray().length + postDataByteArrayImage.toByteArray().length);
urlConnection.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundry);
out = urlConnection.getOutputStream();
out.write(postDataByteArray.toByteArray());
out.write(postDataByteArrayImage.toByteArray());
out.close();
}
int response = 0;
try {
response = urlConnection.getResponseCode();
} catch (IOException e) {
if (e.toString()
.equals("java.io.IOException: Received authentication challenge is null"))
throw new RESTException(401, "Invalid Phone or Pin");
else
throw e;
}
if (response == HttpURLConnection.HTTP_OK) {
is = urlConnection.getInputStream();
if (is == null) {
return new IOException(
"Cannot open HTTP InputStream, aborting");
}
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int ch;
int count = 0;
while ((ch = is.read()) != -1) {
bo.write(ch);
count++;
}
data = bo.toByteArray();
return new String(data);
} else if (response == 500) {
return new RESTException(500, "Internal server error");
} else {
RESTException x = new RESTException();
x.setCode(response);
try {
is = urlConnection.getInputStream();
if (is == null) {
x.setMessage("Unable to retrieve message");
return x;
}
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int ch;
int count = 0;
while ((ch = is.read()) != -1) {
bo.write(ch);
count++;
}
data = bo.toByteArray();
String output = new String(data);
JSONObject obj;
try {
obj = new JSONObject(output);
JSONObject err = obj.getJSONArray("errors")
.getJSONObject(0);
x.setMessage(err.getString("message"));
} catch (JSONException e) {
Log.e("stuff", output);
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// Damn you android! I'm using a REST service here, stop
// trying to interpret my errors!
x.setMessage("Unable to retrieve message");
}
return x;
}
} catch (Exception x) {
x.printStackTrace();
/*
* if (!retried && x.toString().equals(
* "java.io.IOException: Persistent connection dropped after first chunk sent, cannot retry"
* )) { retry = true; } if (!retry) { return x; }
*/
return x;
} finally {
try {
out.close();
} catch (Exception x) {
}
try {
is.close();
} catch (Exception x) {
}
try {
c.close();
} catch (Exception x) {
}
params.clear();
}
// return null;
}
After a very long time of frustration, we discovered that Android tries to keep a connection alive even if you manually call .close() on the connection. This worked fine for our GET methods, but POST methods left the socket in a state that it couldn't then process a GET. Adding the following fixed all our problems:
urlConnection.setRequestProperty("connection", "close");
Has anyone tried this api ? I'm having some trouble implementing it on BlackBerry. Tweets do not always send and I cannot access posted tweets.
Here is my code -
private void twitterSetup(){
HttpRequest req = new HttpRequest("https://api.twitter.com/oauth/access_token");
req.setMethod(HttpConnection.POST);
XAuthSigner signer = new XAuthSigner("", "");
signer.signForAccessToken(req, "", "");
try {
HttpResponse resp = req.send();
if (resp.getCode() == HttpConnection.HTTP_OK)
{
Token accessToken = Token.parse(resp.getBodyContent());
req.close();
req = new HttpRequest("http://api.twitter.com/1/statuses/update.xml");
req.setMethod(HttpConnection.POST);
req.setBodyParameter("status", "new message");
req.setSigner(signer, accessToken);
resp = req.send();
Tweet[] twts = null;
try {
Credential c = new Credential("","","","");
UserAccountManager uam = UserAccountManager.getInstance(c);
List[] lists = null;
ListManager ter = null;
if (uam.verifyCredential()) {
ter = ListManager.getInstance(uam); //pode ser pela classe Timeline tambem.
ListManager listMngr = ListManager.getInstance(uam);
lists = listMngr.getLists();
}
ter.startGetListTweets(lists[0], null, new SearchDeviceListener() {
public void searchCompleted() {}
public void searchFailed(Throwable cause) {}
public void tweetFound(Tweet tweet) {
System.out.println(tweet);
}
});
}
catch(Exception e){
e.printStackTrace();
}
}
else { }
} catch (IOException e) {
e.printStackTrace();
}
catch(Exception e){
}finally {
try {
req.close();
} catch (IOException e) {}
}
}
Thanks for any help.
Ok,
Here is the class im using to get the twitter content based on type and tag. method getContent is not the most elegant but it works. It just downloads and parses a json file.
Look at http://search.twitter.com/api/
public class GetTwitterContent implements Runnable {
private String tag;
private String type;
public GetTwitterContent(String type, String tag) {
this.type = type;
this.tag = tag;
}
public void run() {
try {
Hashtable twitterValuesHashtable = new Hashtable();
String serviceUrl = "";
if (type.equalsIgnoreCase(Constants.TWITTER_CONTENT_TYPE_HASHTAG)) {
serviceUrl = Constants.TWITTER_CONTENT_HASHTAG_CONTENT;
} else if (type.equalsIgnoreCase(Constants.TWITTER_CONTENT_TYPE_USER)) {
serviceUrl = Constants.TWITTER_CONTENT_USER_CONTENT;
}
ByteArrayOutputStream baos = getContent(serviceUrl + this.tag);
JSONObject jsonObject = new JSONObject(new String(baos.toByteArray(), 0, baos.size(), "utf-8"));
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int counter = 0; counter < jsonArray.length(); ++counter) {
JSONObject thisJsonObject = (JSONObject) jsonArray.get(counter);
TwitterResponse twitterResponse = new TwitterResponse();
twitterResponse.setCreatedAt(thisJsonObject.optString("created_at", "na"));
twitterResponse.setTweetText(thisJsonObject.optString("text","na"));
twitterResponse.setFromUser(thisJsonObject.optString("from_user", "na"));
twitterValuesHashtable.put(new Integer(counter),twitterResponse);
}
ServerContent.future.addContent(Constants.TWITTER_KEY, twitterValuesHashtable);
} catch (Exception e) {
e.printStackTrace();
}
}
private ByteArrayOutputStream getContent(String url) {
ByteArrayOutputStream baos = null;
// len = 0;
try {
javax.microedition.io.HttpConnection connection = (javax.microedition.io.HttpConnection) Connector
.open(url);
connection.setRequestMethod(HttpConnection.GET);
// connection.setRequestProperty("Connection", "close");
java.io.InputStream inputStream = connection.openDataInputStream();
// inputStream = getClass().getResourceAsStream(url);
baos = new ByteArrayOutputStream();
int c;
while (true) {
c = inputStream.read();
if (c == -1)
break;
// ++len;
baos.write(c);
}
} catch (Exception e) {
e.printStackTrace();
}
return baos;
}
}