How can i do a http get request in Blackberry - java

i have to do a http GET request on the URL http://api.twitter.com/1/users/show.json?screen_name=Kaka and i will get a JSON object, but i don't know how i have to do it.
Anyone could help me?
Thanks you.

This BlackBerry code sample shows how you do that
Or, From another fairly simple example, that uses the org.json.me package added to BlackBerry Java 6.0:
HttpConnection conn = null;
InputStream in = null;
ByteArrayOutputStream out = null;
try {
String url = "http://api.twitter.com/1/users/show.json?screen_name=Kaka";
conn = (HttpConnection) Connector.open(url, Connector.READ);
conn.setRequestMethod(HttpConnection.GET);
int code = conn.getResponseCode();
if (code == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
out = new ByteArrayOutputStream();
byte[] buffer = new byte[in.available()];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer);
}
out.flush();
String response = new String(out.toByteArray());
JSONObject resObject = new JSONObject(response);
String key = resObject.getString("Insert Json Key");
Vector resultsVector = new Vector();
JSONArray jsonArray = resObject.getJSONArray("Insert Json Array Key");
if (jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length();i++) {
Vector elementsVector = new Vector();
JSONObject jsonObj = jsonArray.getJSONObject(i);
elementsVector.addElement(jsonObj.getString("Insert Json Array Element Key1"));
elementsVector.addElement(jsonObj.getString("Insert Json Array Element Key2"));
resultsVector.addElement(elementsVector);
}
}
}
} catch (Exception e) {
Dialog.alert(e.getMessage());
} finally {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
if (conn != null) {
conn.close();
}
}
Obviously, in the second example, you have to insert the names of the JSON keys that your JSON data actually uses (left as an exercise for the poster). Also, you'll probably know something about how the JSON objects are structured, as objects, and arrays, etc. So, your code for unpacking the JSON data into JSONObjects and JSONArrays may look a little different than above, depending on the structure of your own JSON data.

Related

Android JSON post request with Ruby Web Application connection

I'm trying to connect Android json output with Ruby web application.
I'm having difficulty to connect Android json post request with receiving from Ruby app. When Android jsonobject has another jsonobject inside, it is not recognised in the ruby app. Here is my code.
Android Code
JSONObject events_array = new JSONObject();
JSONObject parent=new JSONObject();
for (int i = 0; i < classtimeList.size(); i++) {
events_array.put(classtimeList.get(i).toString(),priorityList.get(i).toString());
}
parent.put("token","token_information");
parent.put("class_type", "something");
parent.put("class_frequency", "5");
parent.put("course_id", "20");
parent.put("events_array", events_array);
String urlParameters = "info="+parent.toString();
Log.i("parameters", urlParameters);
This is a log info for parameters.
info={"token":"token_information","class_type":"something","class_frequency":"5","course_id":"20","events_array":{"3074":"3","3134":"1","3140":"1","3146":"3","3152":"1","3075":"3","3076":"3","3077":"3","3078":"3","3079":"3","3216":"3","3217":"3","3218":"1","3219":"3"}}
I pass this information to Ruby app and I am having difficulty to extract "events_array" information. Below is my Ruby Code.
My full Android code looks like
class apply extends AsyncTask<String, String, String> {
ProgressDialog pd;
private Exception exception;
protected void onPreExecute() {
pd = new ProgressDialog(ClassApply2.this);
pd.setMessage("loading");
pd.show();
}
protected String doInBackground(String... args) {
String token = args[0];
try {
URL url = new URL("https://www.ringleplus.com/api/v1/apply/test");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
JSONObject events_array = new JSONObject();
JSONObject parent=new JSONObject();
for (int i = 0; i < classtimeList.size(); i++) {
events_array.put(classtimeList.get(i).toString(),priorityList.get(i).toString());
}
parent.put("token","token_information");
parent.put("class_type", "something");
parent.put("class_frequency", "5");
parent.put("course_id", "20");
parent.put("events_array", events_array);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
String urlParameters = "info=" + parent.toString();
DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
dStream.writeBytes(urlParameters);
//dStream.write(data); // <!-- 여기에 url parameter가 들어감
dStream.flush();
dStream.close();
Log.i("parameters", parent.toString());
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line).append("\n");
}
reader.close();
connection.disconnect();
JSONObject jsonObj = null;
jsonObj = new JSONObject(buffer.toString().trim());
String output = jsonObj.getString("item");
return output;
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
//progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
if (pd != null) {
pd.dismiss();
}
adapter.notifyDataSetChanged();
}
Ruby Code
post :test do
parsed_json = ActiveSupport::JSON.decode(params[:info].to_json)
token = parsed_json["token"]
events_array = parsed_json["events_array"]
output = Array.new
if events_array != nil
events_array.each do |start_time, priority|
if priority.to_i == 1 || priority.to_i == 2
userapply = Userapply.new
userapply.classtime_id = start_time
userapply.user_id = user.id
userapply.priority = priority
userapply.save
output << {:userapply_id => userapply.id, :classtime_id => userapply.classtime_id, :user_id => userapply.user_id, :priority => userapply.priority}
end
end
end
return {status: 'ok', item: events_array}
end
What it supposed to be returned is the information about events_array (i.e. {"3074":"3","3134":"1","3140":"1","3146":"3","3152":"1","3075":"3","3076":"3","3077":"3","3078":"3","3079":"3","3216":"3","3217":"3","3218":"1","3219":"3"} )
but, the Android output log is
I/INFO: events_array
but the token extraction seems working.
token = parsed_json["token"]
If this works, then my gut feeling is parsed_json["events_array"] also should work in some sense. But I'm not stuck here.
If this is resolved, then I want to receive parsed_json["events_array"] as a hash information and want to process the full code and get the "output" instead of events_array to check why this doesn't work.
Please let me know if there is anything I'm missing. I really need some help.
Looking forward to seeing anyone's reply.
I finally figured out where the problem came from. I compared what you send to your server with curl in comment above, and what you try to send from android. And these two things are completly difirent. To send the same from androdid, you should form your urlParameter like that:
JSONObject info = new JSONObject();
info.put("info",parent);
urlParameters = info.toString();
And don't forget to do connection.setRequestProperty("Content-Type", "application/json") after connection.setDoOutput(true).
I tested it outside android, and it returned pretty the same as curl command from your comment above. It should work just fine in android.
PS: Please, be more more attentive next time.

converting images to base64 and sending as json

I am trying to convert images i have to base64 then send them as part of a JSON string and all is going ok except when I have 2 images. What happens is i only get the 2nd image twice in the JSON and on the server side but Im failing to see why this is happening..
Here is my code:
JSONObject jsonPhotos = new JSONObject();
if (photos != null) {
try {
JSONArray jsonObj = new JSONArray(photos);
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String imageUrl = c.getString("url");
System.out.println( "each urls: " + imageUrl );
String cap = c.getString("caption");
//get to base64
Bitmap bm = BitmapFactory.decodeFile(imageUrl);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 10, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
String encodedString = Base64.encodeToString(b, Base64.DEFAULT);
jsonPhotos.put( "imageData", encodedString);
jsonPhotos.put( "caption", cap);
claim.accumulate( "photos", jsonPhotos);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
in my log each url is different. but when it gets put into the json the base64 encoded strings are the same.
Create a new jsonPhotos item on every iteration of the loop.
What's happening is that you create a single JSON object before the loop starts, and then you are continually updating it's "itemData" through every iteration of the loop.
I suspect that "claim.accumulate" is holding on to a reference of the JSONObject passed into it instead of making a deep copy. This should fix it.
if (photos != null) {
try {
JSONArray jsonObj = new JSONArray(photos);
for (int i = 0; i < jsonObj.length(); i++) {
...
JSONObject jsonPhotos = new JSONObject(); // add this line here
jsonPhotos.put( "imageData", encodedString);
jsonPhotos.put( "caption", cap);
claim.accumulate( "photos", jsonPhotos);
}

Decoding HttpEntity into android string - encoding issue

I know that should be basics but i had no formation :( and I don't understand it, everywhere it seems obvious to people. I get that one side encode data with his set and android is probably expecting another one, but what can I do to translate?
My app perform a get request on google maps api to retrieve an address from a Lat/lng. But I failed to decode properly the result as a French è is displayed as è
I have not enough xp in Java to understand what to do. It is linked with UTF-8, right?
What should I do?
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
JSONObject jsonObject = new JSONObject();
jsonObject = new JSONObject(stringBuilder.toString());
retList = new ArrayList<Address>();
if("OK".equalsIgnoreCase(jsonObject.getString("status"))){
JSONArray results = jsonObject.getJSONArray("results");
for (int i=0;i<results.length();i++ ) {
JSONObject result = results.getJSONObject(i);
String indiStr = result.getString("formatted_address");
Address addr = new Address(Locale.ITALY);
addr.setAddressLine(0, indiStr);
Dbg.d(TAG, "adresse :"+addr.toString());
retList.add(addr);
}
}
Thanks for help !
Try using UTF-8,
instead of using InputStream try something like,
String responseBody = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
you can use BufferReader
your code will be like this:
InputStream stream = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
int b;
while ((b = br.read()) != -1) {
stringBuilder.append(b);
}

How to reduce the time for sending data to remote server?

E.g. there are 10MB data stored in my tablet. The data has a list structure. Each entry in the list is about 3500 Bytes.
Currently, I send one entry each time with the following codes:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(ipport+ phpHandler);
HttpResponse response = null;
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
response = httpclient.execute(httppost);
} catch (UnsupportedEncodingException e) {
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
But to send this 10MB data, it took a long time. Each sending of an entry takes about 1 second.
Any solution to improve the efficiency?
You can build a JSON string object which contains all the entities and then compress it with gzip or any other compression scheme.
The benefit of building a JSON object is you can transmit all the objects as one request, instead of sending it separately. This would eliminate the latency of establishing a new connection everytime.
// your data list = listData
JSONArray newArray = new JSONArray();
for (int i = 0, lsize = listData.size(); i < lsize; i++) {
try {
newArray.put(i, listData.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
This code would build a JSONArray with all the elements in the listData (it should be a list of strings)
now you can easily convert the JSONArray to a string using
newArray.toString()
Now you can send this JSON string over the network, and you can easily deserialize a JSON object in any server side language.
As for Gzip compression, you might want to look at this link
Here is a question on SO about sending GZip compressed data over HTTP in android
GZip POST request with HTTPClient in Java
I am agreeing with the answer of #Ahmed. you better use jSON string object then compress using gzip libray.
for JSON there are lots of helpful tutorials. following link is really helpful
http://www.vogella.com/articles/AndroidJSON/article.html
here you can see the simple way to write json
public void writeJSON() {
JSONObject object = new JSONObject();
try {
object.put("name", "Jack Hack");
object.put("score", new Integer(200));
object.put("current", new Double(152.32));
object.put("nickname", "Hacker");
} catch (JSONException e) {
e.printStackTrace();
}
}
and to compress and decompress using gzip Here i am adding some sample codes from the answer https://stackoverflow.com/a/6718707/931982
public static byte[] compress(String string) throws IOException {
ByteArrayOutputStream os = new ByteArrayOutputStream(string.length());
GZIPOutputStream gos = new GZIPOutputStream(os);
gos.write(string.getBytes());
gos.close();
byte[] compressed = os.toByteArray();
os.close();
return compressed;
}
public static String decompress(byte[] compressed) throws IOException {
final int BUFFER_SIZE = 32;
ByteArrayInputStream is = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(is, BUFFER_SIZE);
StringBuilder string = new StringBuilder();
byte[] data = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = gis.read(data)) != -1) {
string.append(new String(data, 0, bytesRead));
}
gis.close();
is.close();
return string.toString();
}

HttpURLConection - JSON Response isn't Complete

I am trying to send a request to the Grooveshark API using POST Payload and their requested methods, and I have found a problem. Allow me to show you my code first.
public void getResponse() throws Exception
{
if(service.equals("Grooveshark")) link += getHmacMD5(privateGroovesharkKey, jsonInfo.toString());
if(requestedMethod.equals("GET")) infoURL = new URL(link+arguments);
else infoURL = new URL(link);
HttpURLConnection connection = (HttpURLConnection) infoURL.openConnection();
connection.setRequestMethod(requestedMethod);
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
if(service.equals("Grooveshark"))
{
connection.setRequestProperty("Content-Type","application/json");
OutputStream output = connection.getOutputStream();
output.write(jsonInfo.toString().getBytes());
}
else if(requestedMethod.equals("POST") || requestedMethod.equals("PUT"))
{
OutputStream output = connection.getOutputStream();
output.write(arguments.getBytes());
}
connection.connect();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null)
sb.append(line).append('\n');
setJsonResult(sb.toString());
System.out.println(jsonResult);
jsonFinal = new JSONObject(jsonResult);
connection.disconnect();
}
I have got that code up here in my project, and I can successfully send requested to any API Webservice that uses JSON in their responses. Now there's only a problem: In Android, it does not give me the WHOLE answer. I've tried running the code on a separate Java (no Android) project, and I get the following output. Although, if I run it on Android, the Log shows me the following:
{"header":{"hostname":"RHL073"},"result":{"songs":[{"SongID":5443351,"SongName":"??????\u00b7???? (FINAL FANTASY XII????)","ArtistID":713,"ArtistName":"Final Fantasy","AlbumID":898007,"AlbumName":"Final Fantasy XII Original Soundtrack","CoverArtFilename":"","Popularity":1214500005,"IsLowBitrateAvailable":tr
And it stops on that tr. Has it anything to do with the parsing of the file that I actually apply afterwards? I don't think it is, but just in case, here it is [This is how I call the search, JSONHandler being the object that contains the code provided above]:
public void performSearch() throws Exception
{
JSONObject search = new JSONObject();
search.put("method", method);
JSONObject header = new JSONObject();
header.put("wsKey", key);
JSONObject parameters = new JSONObject();
parameters.put("query", getSearchQuery());
parameters.put("country", "Portugal");
parameters.put("limit", limit);
parameters.put("offset", "");
search.put("header", header);
search.put("parameters", parameters);
JSONHandler jsonHandler = new JSONHandler(link, search, "Grooveshark", "POST", "");
JSONObject finalResult = jsonHandler.getJsonFinal();
JSONArray songs = finalResult.getJSONObject("result").getJSONArray("songs");
ArrayList<Result> allResults = new ArrayList<Result>();
for(int i = 0; i < songs.length(); i++)
{
JSONObject inner = (JSONObject) songs.get(i);
String name = inner.getString("SongName");
int ID = inner.getInt("SongID");
String artist = inner.getString("ArtistName");
Result res = new Result(name, artist, ID);
res.setAlbumName(inner.getString("AlbumName"));
boolean low = inner.getBoolean("IsLowBitrateAvailable");
int bit = 0;
if(low) bit = 1;
else bit = 0;
res.setIsLowBitRateAvailable(bit);
}
setResults(allResults);
}
As you can clearly see, I am using the json.org library. I really don't understand what's the problem here. Has anyone got any idea as to why?

Categories