Blackberry how to get Json Response (java) - json

I want to get a JSON response on the simulator. How can I read JSON from the server?
public void run()
{
HttpConnection httpConn;
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection("http://example.com/login.php");
if (connDesc != null)
{
try {
httpConn = (HttpConnection)connDesc.getConnection();
final int iResponseCode = httpConn.getResponseCode();
Dialog.alert("Type: "+httpConn.getType());
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Response code: " + Integer.toString(iResponseCode));
}
});
}
catch (IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
}

HttpConnection connection = (HttpConnection)Connector.open(urlConection);
InputStream inputStream = connection.openInputStream();
if(connection.getResponseCode() == HttpConnection.HTTP_OK){
InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
int readCharacter;
StringBuffer responseBuffer = new StringBuffer();
while ((readCharacter = reader.read()) != -1) {
responseBuffer.append((char) readCharacter);
connection.close();
inputStream.close();
reader.close();
String responseMessage = new String(responseBuffer);
}
}
You need to create JSONObject for the response.
try {
JSONObject object = new JSONObject(responseMessage);
} catch (JSONException e) {
e.printStackTrace();
}

Related

Java/Android: Backslashes in JSON in Double Quotation places

I try to send "POST" request to serwer. Request includes JSON. Server returns "ok" or my JSON (in value of "message" key), if data in not correct. And I get strange backslashes ( \ sing) in my JSON, sent to server.
I get JSON response:
{"message":{"{\"phone_number\":\"_380661111111\",\"password\":\"112233aa\",\"military_id\":\"12345\",\"email\":\"won#mail_ru\"}":""}}
Normal JSON:
{"phone_number":"380666320670","password":"112233aa","military_id":"12345","email":"wovilon#mail.ru"}
Full code:
class SendLoginData extends AsyncTask<Void, Void, Void> {
String[] key,value;
String mResultString;
SendLoginData(String[] inKey, String[] inValue ){
this.key=new String[inKey.length];
this.value=new String[inValue.length];
this.key=inKey;
this.value=inValue;
}
String resultString = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {// http://oasushqg.beget.tech/users
String myURL = "http://y937220i.bget.ru/users";
byte[] data = null;
InputStream is = null;
try {
URL url = new URL(myURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStream os = conn.getOutputStream();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
for (int i=0; i<this.key.length; i++) {
jsonParam.put(this.key[i], this.value[i]);
}
data=jsonParam.toString().getBytes("UTF-8");
os.write(data);
Log.d("MyLOG", "data is next: "+new String(data, "UTF-8"));
data = null;
conn.connect();
int responseCode= conn.getResponseCode();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (responseCode == 200) {
is = conn.getInputStream();
byte[] buffer = new byte[8192]; // Такого вот размера буфер
// Далее, например, вот так читаем ответ
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
data = baos.toByteArray();
resultString = new String(data, "UTF-8");
JSONObject jsonObj=new JSONObject(resultString);
mResultString=jsonObj.getString("message");
} else {
}
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (Exception e) {
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if(resultString != null) {
Log.d("MyLOG", "postExecute run");
Log.d("MyLOG", mResultString);
}
}}

Json Parse Failed- javafx

I am writing javafx app
I try to sava and load data using JSON
#FXML
private void OpenEvent(ActionEvent event) throws IOException, ParseException, Exception {
String jsonString = new String();
FileReader fileReader = new FileReader("test.json");
BufferedReader bufferedReader = new BufferedReader(fileReader);
System.out.println("Check open event here");
String inputLine;
while ((inputLine = bufferedReader.readLine()) != null) {
jsonString += inputLine;
}
bufferedReader.close();
System.out.println(jsonString);
//GOOD HERE
JSONArray jlist;
try {
jlist = parseJsonArray(jsonString);
} catch (Exception ex) {
throw ex;
}
for (Object e : jlist) {
try {
JSONObject jentryParsed = (JSONObject) e;
LocalEvent entry = new LocalEvent();
entry.initFromJsonString(jentryParsed.toJSONString());
} catch (Exception ex) {
throw ex;
}
}
}
public JSONArray parseJsonArray(String jsonString) throws Exception {
JSONArray jlist;
JSONParser parser = new JSONParser();
System.out.println("Check parse here");
System.out.println(jsonString);
try {
jlist = (JSONArray) parser.parse(jsonString);
} catch (Exception ex) {
throw ex;
}
System.out.println("parsed finished");
if (jlist == null) {
System.out.println("jlist is null");
return null;
} else {
return jlist;
}
}
and here is my JSON file
[{"Description":"11111","Name":"11111","Datetime":2016-04-27},{"Description":"2222","Name":"2222","Datetime":2016-04-14}]
error:
Caused by: Unexpected token VALUE(-4) at position 54.
at org.json.simple.parser.JSONParser.parse(JSONParser.java:257)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:81)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:75)
at todolist.MainController.parseJsonArray(MainController.java:276)
at todolist.MainController.OpenEvent(MainController.java:250)
... 50 more
It seems the json parse is failed.
is here anything wrong with my JSON file?
Thanks!!!!!!!
or the parse cannot recognize "-" in the datetime??

Converting finalBufferData into img url to display

I am trying to extract several images url constructed from parts of a JSON to be displayed.
I was able to retrieve the JSON and then construct several url from the JSON displaying it as a text on the screen ( String ).
at the end of the AsyncTask i used the Universal Image Loader, to display a single pic, in case the JSON contain information of a single pic, but the problem is whnen construct several url from the JSON :
finalBufferData.append("http://res.cloudinary.com/CLOUD_NAME/" + fileType +
"/upload/v" + version + "/" + publicID + "." + format + "/n");
it create a string of address just in separate lines ( if displayed in a textView), but bening passed to UIL it is not acceptable.
So i am not sure how to do this, since i am trying to have an image view within a listView in a linearway or differently maybe, to display several images, depending on the JSON information .
Any suggestion on how to do this will be great .
My AsyncTask code it;
public class JsonTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("resources");
StringBuffer finalBufferData = new StringBuffer();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
String publicID = finalObject.getString("public_id");
String version = finalObject.getString("version");
String format = finalObject.getString("format");
finalBufferData.append("http://res.cloudinary.com/CLOUD_NAME/" + fileType +
"/upload/v" + version + "/" + publicID + "." + format);
}
return finalBufferData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ImageLoader.getInstance().displayImage(result, imageViewDisplayUp);
//imagesList.setText(result);
}
}
}
found a way around it, by adding another String which is not in the JSON but get created from other JASON strings.
Since the public_id, version, and format are in the JSON downloaded from Cloudinary and needed to build the right address for the images to be passed into the ImageLoader, and i couldnt not find another way to retrieve a list of images urls uploaded by the user with a specific tag to Cloudinary, without using the admin api which require writing api_secret in the program, i ended up doing the following;
public class JsonTask extends AsyncTask<String, String, List<upImgModels> > {
#Override
protected List<upImgModels> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("resources");
List<upImgModels> upImgList = new ArrayList<>();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
upImgModels upImgModels = new upImgModels();
upImgModels.setPublic_id(finalObject.getString("public_id"));
upImgModels.setVersion(finalObject.getString("version"));
upImgModels.setFormat(finalObject.getString("format"));
upImgModels.setAddress("http://res.cloudinary.com/we4x4/" + fileType
+ "/upload/v" + finalObject.getString("version") + "/"
+ finalObject.getString("public_id") + "." +
finalObject.getString("format"));
upImgList.add(upImgModels);
}
return upImgList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<upImgModels> result) {
super.onPostExecute(result);
upImgAdapter adapter = new upImgAdapter(getApplicationContext(), R.layout.row, result);
listViewUpload.setAdapter(adapter);
//imagesList.setText(result);
}
}
public class upImgAdapter extends ArrayAdapter{
public List<upImgModels> upImgModelsList;
private int resource;
private LayoutInflater inflater;
public upImgAdapter(Context context, int resource, List<upImgModels> objects) {
super(context, resource, objects);
upImgModelsList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = inflater.inflate(R.layout.row, null);
}
ImageView imageViewDisplay;
imageViewDisplay = (ImageView)convertView.findViewById(R.id.imageViewDisplay);
ImageLoader.getInstance().displayImage(upImgModelsList.get(position).getAddress(), imageViewDisplay);
return convertView;
}
}
}
I hope someone could suggest a better way to do this if it is possible, which i am sure that is the case.

Login android project into localhost server

This is my Code:
public void CheckUserNameandPwd() {
// TODO Auto-generated method stub
String username = u.getText().toString().trim();
String pwd=pwdd.getText().toString().trim();
if(username.length()==0){
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Fill UserName!");
dlgAlert.setTitle("Error");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
return;
}
else if(pwd.length()==0 ){
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Fill Password!");
dlgAlert.setTitle("Error");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
return;
}
else{
if(verifyLogin(username,pwd)){
Toast.makeText(getApplicationContext(),"Login Success",Toast.LENGTH_SHORT).show();
startActivity(new Intent(Login.this,MainActivity.class));
}else{
Toast.makeText(getApplicationContext(),"error occur!",Toast.LENGTH_SHORT).show();
// startActivity(new Intent(Login.this,mainlayout_activity.class));
}
}
}
private boolean verifyLogin(St
ring username, String pwd) {
try{
showpDialog();
DefaultHttpClient httpclient=new DefaultHttpClient();
HttpGet httpget=new HttpGet("http://127.0.0.1:8083/MyService.svc/LoginForUsers?UserName=" + username + "&Password=" + pwd);
HttpResponse httpresponse=httpclient.execute(httpget);
HttpEntity httpentity=httpresponse.getEntity();
InputStream stream=httpentity.getContent();
String result=ConvertStreamToString(stream);
if(result.charAt(1)=='1'){
hidepDialog();
return true;
}else {
hidepDialog();
return false;
}
}catch (Exception e){
hidepDialog();
return false;
}
}
private String ConvertStreamToString(InputStream is) {
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
StringBuffer sb=new StringBuffer();
String line=null;
try
{
while ((line=reader.readLine())!=null){
sb.append(line+"\n");
}
}catch (IOException e){
e.printStackTrace();
}finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Never use a GET request to your server if you have a password on the url!!
Here's a POST request that may help you. Taken from here
...
// Create data variable for sent values to server
String data = URLEncoder.encode("user", "UTF-8")
+ "=" + URLEncoder.encode(Login, "UTF-8");
data += "&" + URLEncoder.encode("pass", "UTF-8")
+ "=" + URLEncoder.encode(Pass, "UTF-8");
String text = "";
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL("http://androidexample.com/media/webservice/httppost.php");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
...

JSON Parsing on BlackBerry

I'm working on parsing JSON on BlackBerry using org.json.me, but I can't parsing the result. Simulator Console says: No Stack Trace
Here's my code to parsing JSON after receiving JSON string from my restclient
try {
JSONObject outer=new JSONObject(data);
JSONArray ja = outer.getJSONArray("status");
JSONArray arr=ja.getJSONArray(0);
System.out.println(arr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And here's the piece code to get JSON from the server
public PromoThread(final String url, final ResponseCallback callback){
Thread t = new Thread(new Runnable(){
public void run() {
waitScreen = new WaitPopupScreen();
System.out.println("Log >> Promo thread run...");
synchronized (UiApplication.getEventLock()){
UiApplication.getUiApplication().pushScreen(waitScreen);
}
//network call
try {
conn = (HttpConnection) new ConnectionFactory().getConnection(url).getConnection();
conn.setRequestMethod(HttpConnection.GET);
conn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Confirguration/CLDC-1.0");
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
in = conn.openInputStream();
// parser.parse(in, handler);
//buff.append(IOUtilities.streamToBytes(in));
//result = buff.toString();
results = new String(IOUtilities.streamToBytes(in));
//System.out.println("Log >> Result: " + results);
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {
//UiApplication.getUiApplication().popScreen(waitScreen);
callback.callback(results, waitScreen);
}
});
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
//start thread
t.start();
}
Thanks for your help