#Path("/getVersion")
#POST
#Produces(MediaType.APPLICATION_JSON)
public String getVersion(String getVersionJson) {
String version = "", patches = "", connectionStatus = "", output1 = "", output2 = "";
try {
JSONObject inputJson = new JSONObject(getVersionJson);
String ip = inputJson.getString("ipaddress").trim();
String userName = inputJson.getString("username").trim();
String passWord = inputJson.getString("password").trim();
connectionStatus = getSSHConnection(ip, userName, passWord);
if (connectionStatus.equals("Connected")) {
//Version Check
expect.send("bwshowver" + "\n");
if (expect.expect("$") > -1) {
String contt = "";
contt = (expect.before);
if (contt != null && contt != "") {
contt = contt.replaceAll("\n+", "\n");
contt = contt.replaceAll(" +", " ");
String splitter[] = contt.split("\n");
for (int i = 0; i < splitter.length; i++) {
//
if (splitter[i].contains("Patches")) {
patches = splitter[i];
}
//version
if (splitter[i].contains("version")) {
version = splitter[i];
}
// output1=version.toString();
// output2=patches.toString();
// output3=output1+output2;
//
output1 = contt;
}
}
} else {
output1 = "Error in version check";
System.out.println("Error in version check");
}
} else {
output1 = connectionStatus;
System.out.println(connectionStatus);
}
} catch (Exception e) {
output1 = "Error";
// logger.error("Exception in getVersion Function-ServService Class: " + e.getMessage());
} finally {
stopSSH();
}
return output3;
}
//The string which is being passed from getVersion comprises of
[{"ipaddress":"10.253.140.116","password":"c0mcast!","username":"bwadmin"},{"ipaddress":"10.253.140.117","password":"bwadmin!","username":"bwadmin"}]
//My requirement is to access the value of ipaddress and password and username and store items in an array and send them to ConnectionStatus.
JSONArray jsonArr = new JSONArray(getVersionJson);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
//Now you can fetch values from each JSON Object
}
JSONObject class represents just one JSON. This is generally inside braces { and }.
If the expected input getVersionJson is just one JSON object, your code works.
However, you are getting an array of JSON objects in the input string getVersionJson, so you need to use JSONArray class to handle an array of JSON Objects.
This is generally [ { }, { }, { }, ... ]
JSONArray extends List, so it can be iterated to read each JSONObject value.
Here is documentation for reference: Interface JsonArray.
please help, i have some code to show a distance. before i use static code for get lat and long. but i need to get lat and long from user..need help how i can get this latitude and longitude from place_id /.
public void setDirectionMap()
ArrayList list = MainActivity.arrJsonTargetLocation;
JSONObject startLocation = MainActivity.jsonStartLocation;
ArrayList targetLocation = MainActivity.arrJsonTargetLocation;
if( list != null )
{
JSONObject targetLocationList = (JSONObject) list.get(list.size() - 1);
}
LatLng start_point = new LatLng(Double.parseDouble(startLocation.getString(``lat``)),
double.parseDouble(startLocation.getString(``lng``)));
LatLng target_point = new LatLng(Double.parseDouble(targetLocation.indexOf(``lat``)),
double.parseDouble(targetLocation.indexOf(``lng``)));
GoDelivery.geoPoints = new ArrayList<LatLng>();
Log.i(TAG, ``#FROM: `` + start_point.toString() + `` -- #TO : `` + target_point.toString());
System.out.println(``=======================ORDER==================================``);
System.out.println(``#FROM: `` + start_point.toString() + `` -- #TO : `` + target_point.toString());
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
StringBuilder jsonResultsDetail = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(DIRECTION_API_BASE + OUT_JSON);
//sb.append(``&components=country:gr``);
sb.append(``?key=`` + API_KEY);
sb.append(``&origin=`` +
start_point.latitude + ``,`` +
start_point.longitude +
``&destination=`` +
target_point.latitude + ``,`` +
target_point.longitude +
``&avoid=tolls``);
Log.i(TAG, ``Query String: `` + sb.toString());
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
//Log.i(TAG,``===============DIRECTIONS===============``);
//Log.i(TAG,jsonResults.toString());
if (conn != null) {
conn.disconnect();
}
} catch (MalformedURLException e) {
Log.e(LOG_TAG, ``MalformedURL ``, e);
} catch (IOException e) {
Log.e(LOG_TAG, ``IOException ``, e);
} catch () {
Log.e(LOG_TAG, ``Throwable``, e);
}
try {
// double place_id = JSONArray.getDouble(``latitude``);
//double place_id = JSONArray.getDouble(``longitude``);
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONObject jsonLeg = jsonObj.getJSONArray(``routes``).getJSONObject(0).getJSONArray(``legs``).getJSONObject(0);
JSONObject jsonSumDistance = jsonLeg.getJSONObject(``distance``);
JSONObject jsonSumDuration = jsonLeg.getJSONObject(``duration``);
JSONArray jsonSteps = jsonLeg.getJSONArray(``steps``);
JSONObject jsonObjlat = new JSONObject().getJSONObject(``lat``);
JSONObject jsonObjlng = new JSONObject().getJSONObject(``lng``);
Don't worry dude , It is not that to tough
Just pass your place id and your key in this url
This url will return json containing all the info of the place.
once you got json then you need to parse the json string to get the lat and lang .
i try to get multiple table from json, i have two tables ( hotline and other ) , i can get data from hotline table, but cannot get from other table
in my php (json):
{"hotline":[{"id":"2","name_hotline":"Tourist Police","phone_hotline":"192"},{"id":"6","name_hotline":"Water","phone_hotline":"1199"}]}{"other":[{"id":"1","name_other":"Lao National Tourism Administration","phone_other":"+85621212248 ","latitude_other":"0","pic_other":"","longtitude_other":"0"},{"id":"2","name_other":"Tourism Police Department","phone_other":"+85621251128 ","latitude_other":"0","pic_other":"","longtitude_other":"0"}]}
MainActivity.java :
InputStream objInputStream = null;
String strJSON = "";
try {
HttpClient objHttpClient = new DefaultHttpClient();
HttpPost objHttpPost = new HttpPost("http://192.168.1.102/emergencycall/php_get_data.php");
HttpResponse objHttpResponse = objHttpClient.execute(objHttpPost);
HttpEntity objHttpEntity = objHttpResponse.getEntity();
objInputStream = objHttpEntity.getContent();
Log.d("Emergency", "Connected HTTP Success !");
} catch (Exception e) {
Log.d("Emergency", "Error Connect to : " + e.toString());
}
try {
BufferedReader objBufferesReader = new BufferedReader(new InputStreamReader(objInputStream, "UTF-8"));
StringBuilder objStrBuilder = new StringBuilder();
String strLine = null;
while ((strLine = objBufferesReader.readLine()) != null) {
objStrBuilder.append(strLine);
}
objInputStream.close();
strJSON = objStrBuilder.toString();
Log.d("Emergency", "Connected JSON Success !");
} catch (Exception e) {
Log.d("Emergency","Error Convert To JSON :" + e.toString() );
}
try {
JSONObject object = new JSONObject(strJSON);
JSONArray objJSONArray = object.getJSONArray("hotline");
JSONArray objJSONAraay2 = object.getJSONArray("other");
for (int i = 0; i < objJSONArray.length(); i++) {
JSONObject objJSONObject = objJSONArray.getJSONObject(i);
strNameHotlineMySQL = objJSONObject.getString("name_hotline");
strPhoneHotlineMySQL = objJSONObject.getString("phone_hotline");
}
for (int j = 0; j < objJSONAraay2.length(); j++) {
JSONObject objJSONObject1 = objJSONAraay2.getJSONObject(j);
strNameHospitalMySQL = objJSONObject1.getString("name_other");
strPhoneHospitalMySQL = objJSONObject1.getString("phone_other");
long insertID4 = objHotlineTable.addDataFromSQLiteHospital(strNameHospitalMySQL, strPhoneHospitalMySQL, strPicHospitalMySQL);
}
} catch (Exception e) {
Log.d("Emergency","Error syncdata to SQLite :" + e.toString() );
}
and i get an error in Logcat:
: Error syncdata to SQLite :org.json.JSONException: No value for other
Your json data format is not correct. Json data format should be like this:
{
"hotline":[
{
"id":"2",
"name_hotline":"Tourist Police",
"phone_hotline":"192"
},
{
"id":"6",
"name_hotline":"Water",
"phone_hotline":"1199"
}
],
"other":[
{
"id":"1",
"name_other":"Lao National Tourism Administration",
"phone_other":"+85621212248 ",
"latitude_other":"0",
"pic_other":"",
"longtitude_other":"0"
},
{
"id":"2",
"name_other":"Tourism Police Department",
"phone_other":"+85621251128 ",
"latitude_other":"0",
"pic_other":"",
"longtitude_other":"0"
}
]
}
And than,
You can use "Retrofit" and "gson" for http request and object mapping.
I've been trying to use the Forecast.io API and the JAR that was provided by their website for my application. But when making web API calls it looks like the data that is being returned by the site isn't fully downloaded.
I try it print the data and it appears that it is not all the information.
I'm using this code:
HttpClient client = new DefaultHttpClient();
URI website = new URI(requestURL);
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
scanner = new BufferedReader(new inputStreamReader(response.getEntity()
.getContent()));
String availalbe;
while ((availalbe = scanner.readLine()) != null) {
res += availalbe;
}
Data that is printed out (it stops partway through what is expected):
{"latitude":51.7589177,"longitude":-0.2342903,"timezone":"Europe/London","offset":1,"currently":{"time":1370612854,"summary":"Partly Cloudy","icon":"partly-cloudy-day","precipIntensity":0,"temperature":20.65,"dewPoint":10.56,"windSpeed":9.92,"windBearing":59,"cloudCover":0.34,"humidity":0.5,"pressure":1023.91,"visibility":10.75,"ozone":356.06},"minutely":{"summary":"Light rain in 30 min.","icon":"rain","data":[{"time":1370612820,"precipIntensity":0},{"time":1370612880,"precipIntensity":0},{"time":1370612940,"precipIntensity":0},{"time":1370613000,"precipIntensity":0},{"time":1370613060,"precipIntensity":0},{"time":1370613120,"precipIntensity":0},{"time":1370613180,"precipIntensity":0},{"time":1370613240,"precipIntensity":0},{"time":1370613300,"precipIntensity":0},{"time":1370613360,"precipIntensity":0},{"time":1370613420,"precipIntensity":0},{"time":1370613480,"precipIntensity":0},{"time":1370613540,"precipIntensity":0},{"time":1370613600,"precipIntensity":0},{"time":1370613660,"precipIntensity":0.107,"precipIntensityError":0.055,"precipProbability":0.01,"precipType":"rain"},{"time":1370613720,"precipIntensity":0.111,"precipIntensityError":0.057,"precipProbability":0.01,"precipType":"rain"},{"time":1370613780,"precipIntensity":0.132,"precipIntensityError":0.065,"precipProbability":0.01,"precipType":"rain"},{"time":1370613840,"precipIntensity":0.137,"precipIntensityError":0.062,"precipProbability":0.03,"precipType":"rain"},{"time":1370613900,"precipIntensity":0.142,"precipIntensityError":0.065,"precipProbability":0.03,"precipType":"rain"},{"time":1370613960,"precipIntensity":0.161,"precipIntensityError":0.072,"precipProbability":0.04,"precipType":"rain"},{"time":1370614020,"precipIntensity":0.174,"precipIntensityError":0.074,"precipProbability":0.04,"precipType":"rain"},{"time":1370614080,"precipIntensity":0.187,"precipIntensityError":0.077,"precipProbability":0.08,"precipType":"rain"},{"time":1370614140,"precipIntensity":0.207,"precipIntensityError":0.084,"precipProbability":0.09,"precipType":"rain"},{"time":1370614200,"precipIntensity":0.223,"precipIntensityError":0.088,"precipProbability":0.1,"precipType":"rain"},{"time":1370614260,"precipIntensity":0.224,"precipIntensityError":0.094,"precipProbability":0.15,"precipType":"rain"},{"time":1370614320,"precipIntensity":0.243,"precipIntensityError":0.102,"precipProbability":0.16,"precipType":"rain"},{"time":1370614380,"precipIntensity":0.259,"precipIntensityError":0.108,"precipProbability":0.17,"precipType":"rain"},{"time":1370614440,"precipIntensity":0.262,"precipIntensityError":0.108,"precipProbability":0.24,"precipType":"rain"},{"time":1370614500,"precipIntensity":0.28,"precipIntensityError":0.115,"precipProbability":0.25,"precipType":"rain"},{"time":1370614560,"precipIntensity":0.3,"precipIntensityError":0.12,"precipProbability":0.25,"precipType":"rain"},{"time":1370614620,"precipIntensity":0.322,"precipIntensityError":0.125,"precipProbability":0.26,"precipType":"rain"},{"time":1370614680,"precipIntensity":0.33,"precipIntensityError":0.125,"precipProbability":0.33,"precipType":"rain"},{"time":1370614740,"precipIntensity":0.352,"precipIntensityError":0.131,"precipProbability":0.34,"precipType":"rain"},{"time":1370614800,"precipIntensity":0.375,"precipIntensityError":0.136,"precipProbability":0.34,"precipType":"rain"},{"time":1370614860,"precipIntensity":0.38,"precipIntensityError":0.14,"precipProbability":0.42,"precipType":"rain"},{"time":1370614920,"precipIntensity":0.402,"precipIntensityError":0.147,"precipProbability":0.42,"precipType":"rain"},{"time":1370614980,"precipIntensity":0.425,"precipIntensityError":0.154,"precipProbability":0.42,"precipType":"rain"},{"time":1370615040,"precipIntensity":0.432,"precipIntensityError":0.157,"precipProbability":0.5,"precipType":"rain"},{"time":1370615100,"precipIntensity":0.454,"precipIntensityError":0.164,"precipProbability":0.5,"precipType":"rain"},{"time":1370615160,"precipIntensity":0.477,"precipIntensityError":0.168,"precipProbability":0.5,"precipType":"rain"},{"time":1370615220,"precipIntensit
Method calling the Forecast Api test class
public void weatherLike()
{
StrictMode.enableDefaults();
MyLocation myLocation = new MyLocation();
myLocation.getLocation(MyService.this, new LocationResult() {
ForecastIO fio = null;
#Override
public void gotLocation(Location location) {
try {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
fio= new ForecastIO("[API_KEY]");
} catch (Exception e) {
speakOut(user + ", I am not able to locate you");
e.printStackTrace();
}finally
{
System.out.println("Latitude: "+fio.getLatitude());
System.out.println("Longitude: "+fio.getLongitude());
System.out.println("Timezone: "+fio.getTimezone());
System.out.println("Offset: "+fio.offsetValue());
System.out.println("\n");
}
}
});
}
Thanks to all the Answers. i found out that My LogCat was trucating long messages no wonder why i never showed a full reply.
in case any one fell in the same problem.
Split the String reply to pieces using this code
if (sb.length() > 4000) {
Log.v("length", "sb.length = " + sb.length());
int chunkCount = sb.length() / 4000; // integer division
for (int i = 0; i <= chunkCount; i++) {
int max = 4000 * (i + 1);
if (max >= sb.length()) {
Log.v("1st", "chunk " + i + " of " + chunkCount + ":" + sb.substring(4000 * i));
} else {
Log.v("2nd", "chunk " + i + " of " + chunkCount + ":" + sb.substring(4000 * i, max));
}
}
}
BufferedReader use 'buffer' so U have to use 'flush method' (or close method )
refer link : http://docs.oracle.com/javase/tutorial/essential/io/buffers.html
try this
public static String getResponseText(String stringUrl) throws IOException
{
StringBuilder response = new StringBuilder();
System.out.println("webservice 1");
URL url = new URL(stringUrl);
HttpURLConnection httpconn = (HttpURLConnection)url.openConnection();
if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK)
{
System.out.println("webservice 2");
BufferedReader input = new BufferedReader(new InputStreamReader(httpconn.getInputStream()),8192);
String strLine = null;
while ((strLine = input.readLine()) != null)
{
response.append(strLine);
}
input.close();
}
return response.toString();
}
I tried to request a large amount of data from freebase. But I got error message "HTTP response code: 403". Did anyone have similar problem before?
Here is my code
private static final String service_url = "https://www.googleapis.com/freebase/v1/mqlread";
public static void main(String[] args)
{
try
{
String cursor = "";
String urlStr_initial = service_url + "?query=" + URLEncoder.encode(getQuery(), "UTF-8") + "&cursor";
URL url = new URL(urlStr_initial);
List<Freebase> list = new ArrayList<Freebase>();
Freebase f_b;
do
{
HttpURLConnection url_con = (HttpURLConnection)url.openConnection();
url_con.addRequestProperty("User-Agent", "Mozilla/4.76");
StringBuilder str_builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(url_con.getInputStream()));
String line;
while((line = reader.readLine()) != null)
{
str_builder.append(line);
}
String response = str_builder.toString();
JSONObject j_object = new JSONObject(response);
if(j_object.has("result"))
{
JSONArray j_array = j_object.getJSONArray("result");
for(int i = 0; i < j_array.length(); i++)
{
JSONObject j_o = j_array.getJSONObject(i);
if(j_o.has("id") == true && j_o.has("name"))
{
String id = j_o.getString("id");
String name = j_o.getString("name");
System.out.println("ID: " + id + " / Name:" + name);
f_b = new Freebase(id, name);
if(f_b != null)
{
list.add(f_b);
}
else
{
System.out.println("Null value in Freebase");
}
}
}
}
else
{
System.out.println("There is no \"result\" key in JASON object");
}
if(j_object.has("cursor"))
{
cursor = j_object.get("cursor").toString();
}
else
{
cursor = "false";
}
String urlStr = urlStr_initial + "=" + cursor;
url = new URL(urlStr);
}while( !cursor.equalsIgnoreCase("false"));
if(list != null)
{
TextFile tf = new TextFile();
tf.writeToFile(list);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
private static String getQuery()
{
return "[{"
+ "\"name\": null,"
+ "\"id\": null,"
+ "\"type\":\"/people/person\","
+ "\"limit\": 500"
+ "}]";
}
You don't say what "large" is, but the API isn't designed for bulk downloads. You should be using the data dumps for that.
There's usually more detailed error message included with the HTTP response code. If, for example, it says 403 - Forbidden - API key required, it means you didn't include your API key (I don't see where you include it in your code). If it says 403 - Forbidden - quota exceeded it means you've exceeded your request quota (you can look on the API console to see how much quota you have remaining).