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.
I have a problem with connecting to WAMP server with my android program that I made with eclipse....
This is my class:
public class Webservice {
public static String readurl(String url)
{
try {
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost(url);
HttpResponse response = client.execute(method);
InputStream inputStream = response.getEntity().getContent();
String resault = ConvertInputStream(inputStream);
return resault;
}
catch (ClientProtocolException e) {
//e.printStackTrace();
Log.i("Log", "Protocol");
}
catch (IOException e) {
//e.printStackTrace();
Log.i("Log", "IOException");
}
return "read";
}
private static String ConvertInputStream(InputStream inputStream)
{
try
{
BufferedReader reader = new BufferedReader(new
InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
return builder.toString();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
}
And this is my activity code:
public class NotesActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String resault = Webservice.readurl("http://localhost/note-server");
Log.i("Log", "Resault: " + resault);
When I run, it gives me "IOException" because of the "Log" in my class under the IOException, and at the end give me "Result: read"!!!!!
How can I fix that?
If you are running on an emulator then you should use 10.0.2.2 instead of localhost.
See this post.
I am downloading a very huge JSON and it takes a lot of time.
I want to show the percentage of data I have downloaded.
I searched and found how to display progress if downloading a file but not JSON.
Here is how I am downloading JSON
private String getStringFromURL(String url) {
String string = null;
try {
HttpClient client = new DefaultHttpClient();
url = url.replace(" ", "%20");
url = url.replace("|", "%7C");
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(response.getEntity(),
HTTP.UTF_8);
if (result.toLowerCase().contains("invalid"))
return null;
result = result.replace("\r", "");
result = result.replace("\n", "").replace("\t", "\\t")
.replace("\b", "\\b").replace("\f", "\\f")
.replace("&", "\\&").replace("\'", "\\'")
.replace(";", "\\;").replace("?", "\\?")
.replace("*", "\\*");
string = result;
}
} catch (Exception e) {
e.printStackTrace();
}
return string;
}
You better to use AsyncTask to download data. There is a sample code below. I did not test it but it should work.
private class FetchJsonTask extends AsyncTask<Void, Void, String> {
private ProgressDialog progressDialog;
private Context context;
public FetchJsonTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
// set up progress dialog
progressDialog = new ProgressDialog(context);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Please wait...");
// show it
progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String jsonStr = null;
try {
// Construct the URL somehow
URL url = createURL();
// Create the request to MuslimSalat.com, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
jsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the data, there's no point in attemping
// to parse it.
return null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
return jsonStr;
}
#Override
protected void onPostExecute(String jsonString) {
// jsonString is your result use it somehow.
Log.d(LOG_TAG, "Json result: " + jsonString);
// dismiss the progress because downloading process is finished.
progressDialog.dismiss();
}
}
You can call it from your activity, fragment etc.
FetchJsonTask fetchJsonTask = new FetchJsonTask(context);
fetchJsonTask.execute();
I'm trying to POST data in JSON format to a script I have running PHP on my webserver. I have found this post: How to send data to a website using httpPost, app crashes.
Using the code he wrote (putting it on a separate thread first) I am able to post data to the PHP script, which accesses it by the $_POST variable. However, I wish to post my data in JSON format. I am guessing it would require me to post a raw stream of data to the server. What functions are available to achieve this? I would also need to post images as a stream of data to the PHP script so I think this solution will also help me in that area.
Additionally, what are the advantages of posting JSON to the server rather than using the method he used?
I am programming the client side in Java in conjunction with the Android SDK.
Any help would be appreciated.
I have a sample example for posting json data .
Have a look at this:
public class LoginActivity extends Activity {
private static final String TAG = "LoginActivity";
private Context mContext;
private Intent mIntent;
private ProgressDialog pdLoading;
private class LoginTask extends AsyncTask<Void, Void, String>
{
private ArrayList<NameValuePair> mParams = new ArrayList<NameValuePair>();
private JSONArray mJArray = new JSONArray();
private JSONObject mJobject = new JSONObject();
private String jsonString = new String();
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.show();
}
#Override
protected String doInBackground(Void... params) {
try {
mJobject.put("userName", "test");
mJobject.put("password", "test");
mJArray.put(mJobject);
mParams.add(new BasicNameValuePair("message", mJArray.toString()));
jsonString = WebAPIRequest.postJsonData("http://putyoururlhere.com/login.php?", mParams);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return jsonString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pdLoading.dismiss();
if(result!=null)
{
/* try {
mJobject = new JSONObject(jsonString);
if(mJobject.getString("Success").equals("True"))
{
mJArray = mJobject.getJSONArray("user");
JSONObject mUser = mJArray.getJSONObject(0);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
Log.e(TAG, jsonString);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialization();
new LoginTask().execute();
}
private void initialization() {
mContext = this;
mIntent = new Intent();
pdLoading = new ProgressDialog(mContext);
pdLoading.setMessage("loading...");
}
}
and
public class WebAPIRequest {
public static String convertStreamToString(InputStream is)
throws IOException {
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
is.close();
}
return sb.toString();
} else {
return "";
}
}
public static String postJsonData(String url, List<NameValuePair> params) {
String response_string = new String();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
try {
httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
String paramString = URLEncodedUtils.format(params, HTTP.UTF_8);
String sampleurl = url + "" + paramString;
Log.e("Request_Url", "" + sampleurl);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
if (response != null) {
InputStream in = response.getEntity().getContent();
response_string = WebAPIRequest.convertStreamToString(in);
}
} catch (Exception e) {
e.printStackTrace();
}
return response_string;
}
}
EDIT :
try,
print_r(json_decode($_POST['message'], true);
or
$data = file_get_contents('php://input');
$json = json_decode($data,true);
I hope it will be helpful !!
I am developing an android application in which first I am sending request to Web service and getting the response status in 0 or 1 format if I get the response as 1 then complete JSON file is loaded.
My question is I want to make an offline app for which I want to download the JSON data from one activity and read that data in different activity with listview displaying title of every downloaded JSON file. After clicking the listview item, JSON data is displayed. And some of the JSON data items contains URL of images I also want to download them and display them in another activity.
I also want to encrypt the downloaded JSON data. Please Help me.
For reference I have attached the JSON file format.
{"test_time":7200,"time_taken":"0","time_left":"7200","score":null,"easy_score":null,"medium_score":null,"hard_score":null,"status":"n","sections":[{"section_id":"196498","section_name":"Reasoning Aptitude","section_no":1,"total_questions":"40","total_minutes":"24","questions":[{"question_id":"61562","question":{"1":{"text":"In a certain code GRANT is written as UOBSH and PRIDE is written as FEJSQ. How is SOLD written in that code?","image":"","imgHeight":"","imgWidth":""}},"correct_ans":{"1":{"text":"EMPT","image":"","imgHeight":"","imgWidth":""}},"rightOption":[],"rightOptionID":"246408","rightOptionNo":"2","anwer_explaination":{"1":{"text":"","image":"http://abc.com/testengine/images/questions/bankpower/image1.Jpeg","imgHeight":304,"imgWidth":212},"2":{"text":" ","image":"","imgHeight":"","imgWidth":""}},"question_time_taken":"10","marked":"0","skipped":"0","answer_id":"1395795","option_choose":"246407","question_status":1,"options":[{"OptionId":"246406","OptionDesc":{"1":{"text":"EPMT","image":"","imgHeight":"","imgWidth":""}}},{"OptionId":"246407","OptionDesc":{"1":{"text":"TPME","image":"","imgHeight":"","imgWidth":""}}},{"OptionId":"246408","OptionDesc":{"1":{"text":"EMPT","image":"","imgHeight":"","imgWidth":""}}},{"OptionId":"246409","OptionDesc":{"1":{"text":"CKNR","image":"","imgHeight":"","imgWidth":""}}},{"OptionId":"246410","OptionDesc":{"1":{"text":"ETPM","image":"","imgHeight":"","imgWidth":""}}}]},{"question_id":"61563","question":{"1":{"text":"Four of the following five are alike in a certain way and so form a group. Which is the one that does not belong to that group?","image":"","imgHeight":"","imgWidth":""}},"correct_ans":{"1":{"text":"27","image":"","imgHeight":"","imgWidth":""}},"rightOption":[],"rightOptionID":"246414","rightOptionNo":"3","anwer_explaination":{"1":{"text":"Mouse is odd rest are use for storage.","image":"","imgHeight":"","imgWidth":""}},"question_time_taken":"0","marked":"0","skipped":"1","answer_id":"","option_choose":"","question_status":3,"options":[{"OptionId":"246411","OptionDesc":{"1":{"text":"19","image":"","imgHeight":"","imgWidth":""}}},{"OptionId":"246412","OptionDesc":{"1":{"text":"17","image":"","imgHeight":"","imgWidth":""}}},{"OptionId":"246413","OptionDesc":{"1":{"text":"13","image":"","imgHeight":"","imgWidth":""}}},{"OptionId":"246414","OptionDesc":{"1":{"text":"27","image":"","imgHeight":"","imgWidth":""}}},{"OptionId":"246415","OptionDesc":{"1":{"text":"37","image":"","imgHeight":"","imgWidth":""}}}]}
parse all the data using the parser detailed in that link
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
then Write all the data into a file using the method below , this way ur data is downloaded and saved as a file
public void appendData(String text)
{
File myFile = new File("sdcard/myfile.file");
if (!myFile.exists())
{
try
{
myFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(myFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You need to do something like this:
private class PrepareMapTask extends AsyncTask<String, Integer, Boolean>
{
// Initialize with invalid value
private int mPrepareResult = -1;
private String mJsonString = null;
protected Boolean doInBackground(String... urls)
{
mJsonString = downloadFileFromInternet(urls[0]);
if(mJsonString == null /*|| mJsonString.isEmpty()*/)
return false;
JSONObject jObject = null;
try {
jObject = new JSONObject(mJsonString);
JSONArray jsonImageArray = jObject.getJSONArray("imageTarget");
JSONArray jsonUrlArray = jObject.getJSONArray("videoUrls");
JSONArray jsonVideoOrUrlArray = jObject.getJSONArray("videoOrUrl");
if (jsonImageArray == null || jsonUrlArray == null)
return false;
for (int i = 0; i<jsonImageArray.length(); i++){
mapTargetUrl.put(jsonImageArray.get(i).toString(), jsonUrlArray.get(i).toString());
mVideoOrUrl.add(jsonVideoOrUrlArray.get(i).toString());
}
} catch (JSONException e) {
e.printStackTrace();
return false;
}
return true;
}
protected void onPostExecute(Boolean result)
{
}
private String downloadFileFromInternet(String url)
{
if(url == null /*|| url.isEmpty() == true*/)
new IllegalArgumentException("url is empty/null");
StringBuilder sb = new StringBuilder();
InputStream inStream = null;
try
{
url = urlEncode(url);
URL link = new URL(url);
inStream = link.openStream();
int i;
int total = 0;
byte[] buffer = new byte[8 * 1024];
while((i=inStream.read(buffer)) != -1)
{
if(total >= (1024 * 1024))
{
return "";
}
total += i;
sb.append(new String(buffer,0,i));
}
}catch(Exception e )
{
e.printStackTrace();
return null;
}catch(OutOfMemoryError e)
{
e.printStackTrace();
return null;
}
return sb.toString();
}
private String urlEncode(String url)
{
if(url == null /*|| url.isEmpty() == true*/)
return null;
url = url.replace("[","");
url = url.replace("]","");
url = url.replaceAll(" ","%20");
return url;
}
}
Take the data structures as per your json and modify the code.
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);
// Set HTTP parameters
/*StringEntity se;
se = new StringEntity(jsonObjSend.toString());*/
jsonObjSend.length();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(jsonObjSend.length());
nameValuePairs.add(new BasicNameValuePair("data", jsonObjSend.toString()));
// Log.i("jsonObjSend.toString()","jsonObjSend.toString()"+jsonObjSend.toString());
Log.i("HTTPPOST","URL: "+URL);
Log.i("HTTPPOST","Request: "+jsonObjSend.toString());
UrlEncodedFormEntity en=new UrlEncodedFormEntity(nameValuePairs);
en.getContent();
httpPostRequest.getParams().setParameter("http.socket.timeout", new Integer(600000));
httpPostRequest.setEntity(en);
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
Log.i(TAG, httpPostRequest.getRequestLine().getProtocolVersion().toString());
responses = convertEntityToString(response.getEntity(), "UTF-8");
Log.i("HTTPPOST","Responce: "+responses);
Log.i("HTTPPOST","******************");
//Log.i("Encoding",response.getEntity().getContentEncoding().getName());
if (response.equalsIgnoreCase("")) {
webresponse = 1;
} else {
webresponse = 0;
}
} catch (IOException e) {
h.post(new Runnable() {
#Override
public void run() {
pd.dismiss();
AlertNullWebserviceResponce();
}
});
e.printStackTrace();
}