Please have a look at the following code
package com.example.jsontest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText editText;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.edit_text);
//Call The JSon
try {
JSONObject jObject = new JSONObject(getJson());
int code = jObject.getInt("code");
editText.append("Code: "+code+"\n");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String getJson()
{
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://bigml.io/andromeda/source/5277b1bd035d074e940056e0?username=xxx;api_key=xxxxxxxxxxxxxxx");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
}
In here, what I need to do is, print the "entire" result I retrieved. I wish to print the entire thing, I don't need to get separate values. How can I do this? Here is the link to the BigML retrieve documentation.
Just use JSONObject.toString() ?
You should never connect to network on main thread. Best and the most simple option is to use AsyncTask<...>.
something like this:
private class DownloadProductsTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
try {
return new PublicDataDBManager().retriveJsonData(mCode, mUserMail);
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(String result){
buildData(result);// here you update mathod in your main thread
}
}
Here is simple example: http://androide-examples.blogspot.com/2013/11/android-retrieve-json-data-from-url.html
So I ran your code, and it crashed. I also see that you are bypassing security and doing network operations in onCreate, in the main thread. This isn't a good idea in Android. Network operations should go in a background thread.
I refactored it very quickly to use a thread and it worked. Here is the code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.edit_text);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
new Thread(new Runnable() {
#Override
public void run() {
JSONObject jObject;
try {
jObject = new JSONObject(getJson());
// I am logging the raw value that was returned here
Log.i("JSON Body", jObject.toString());
int code = jObject.getInt("code");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
If you want to update the main thread (MainActivity) within the thread, create a Handler and pass a reference to that into the thread, and use that for updates.
Related
I've got a server set up to accept email & password credentials and I want my app to login using HttpURLconnection. The connection part seems to be ok, since the response is alway 200, but I'm having trouble actually sending the data. I convert the json pair to string and send it through DataOutputStream. I read the response through InputStream.
My main problem is the response I read with InputStream is always the same (the html of the login page) even if the email&password are wrong, which has me thinking I'm not sending the data correctly.
You can take a look at my code:
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.JsonWriter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.app.ProgressDialog;
import java.io.DataOutputStream;
import java.net.MalformedURLException;
import android.net.Uri;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.content.Intent;
import org.json.JSONObject;
import org.json.JSONStringer;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private EditText user;
private EditText pswrd;
private Button login;
private String email;
private String password;
private String HOST;
private String DEFAULT_IPADDRESS;
private String PREFERENCES_IPADDRESSSERVER;
private String PREFERENCES_TOKEN;
private Context ctx;
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private String sRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user = (EditText) findViewById(R.id.Email);
pswrd = (EditText) findViewById(R.id.Password);
login = (Button) findViewById(R.id.button);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
email = user.getText().toString();
password = pswrd.getText().toString();
try {
//HttpURLConnection example = serverLogin(email, password);
new AsyncLogin().execute(email, password);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private class AsyncLogin extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address
url = new URL("http://81.169.151.83/users/sign_in");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "exception";
}
try {
// Setup HttpURLConnection class to send and receive data
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
JSONObject request = new JSONObject();
try {
request.put("email", params[0]);
request.put("password", params[1]);
} catch (org.json.JSONException e) {
e.printStackTrace();
}
sRequest = request.toString();
// Open connection for sending data
conn.connect();
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(sRequest);
wr.flush();
wr.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "exception";
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return "exception";
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
if (result.equalsIgnoreCase("true")) {
/* Here launching another activity when login successful. If you persist login state
use sharedPreferences of Android. and logout button to clear sharedPreferences.
*/
Toast.makeText(MainActivity.this, "GREAT SUCCESS", Toast.LENGTH_LONG).show();
/* Intent intent = new Intent(MainActivity.this,SuccessActivity.class);
startActivity(intent);
MainActivity.this.finish();*/
} else if (result.equalsIgnoreCase("false")) {
// If username and password does not match display a error message
Toast.makeText(MainActivity.this, "Invalid email or password", Toast.LENGTH_LONG).show();
} else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {
Toast.makeText(MainActivity.this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();
}
}
}
Thanks
I would recommend you to try OKHTTP, check out their recipes, it is a lot simpler to do GET / POST requests in Android.
On a side note, I've checked out your website at http://81.169.151.83/users/sign_in and the parameters used for the login form is user[email] and user[password]. Not the email and password which you added above. There are also several other form fields such as authenticity_token which might be the cause.
I'm trying to read website data with my Android app. What's strange is that it works on my Android 2.3.4 phone, but not my brand new 2nd Gen Nexus 7 Tablet that's running Android 4.3. I'm not getting any errors in LogCat, there's just nothing displayed on the Tablet. Has anyone else run into this? If so, clue me in to a fix so that it'll run on both my devices. Here's my whole Activity:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class WCBCCalendar extends Activity {
Button back_BTN;
TextView urlTest_TV;
String about_url_Str = "http://www. url to read";
String returned;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar);
back_BTN = (Button) findViewById(R.id.backCal_btn);
sunDate_TV = (TextView) findViewById(R.id.sunDate_TV);
npDate_TV = (TextView) findViewById(R.id.npDate_TV);
urlTest_TV = (TextView) findViewById(R.id.urlTest_tv);
GetWebInfo test = new GetWebInfo();
try {
returned = test.getInternetData();
urlTest_TV.setText(returned);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}// --- END onCreate
// --- Classes, Methods
public class GetWebInfo {
public String getInternetData() throws Exception{
BufferedReader in = null;
String data = null;
try{
HttpClient client = new DefaultHttpClient();
URI website = new URI(about_url_Str);
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity ().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while((l = in.readLine()) !=null ){
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}finally{
if (in != null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}//--- END class
// --- END all Classes, Methods
#Override
protected void onPause() {
super.onPause();
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
}
}
I'm a android noob on programming, but with some help of a few programms I can learn the basics. I would like to do a basic http get request to an arduino ethernetshield.
For this I've found some code, but I can't get it to work.
I'm allways stuck on the getResponse part with the code I've tried from several pages.
I've found the following page which gave me readable code:
How to work with an image using url in android?
Now I've created the following:
Press on a button and do a get to an url:
package adhttpget.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class AdhttpgetActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void pushbutton1(View view) {
Toast.makeText(getBaseContext(), "button press", Toast.LENGTH_SHORT).show();
Log.e("button", "pressed");
URL connectURL = new URL("http://192.168.0.48/?out=13&status=2");
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
// do some setup
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
// connect and flush the request out
conn.connect();
conn.getOutputStream().flush();
// now fetch the results
String response = getResponse(conn); // <-- THIS IS MY PROBLEM
}
private String getResponseOrig(HttpURLConnection conn)
{
InputStream is = null;
try
{
is = conn.getInputStream();
// scoop up the reply from the server
int ch;
StringBuffer sb = new StringBuffer();
while( ( ch = is.read() ) != -1 ) {
sb.append( (char)ch );
}
return sb.toString();
}
catch(Exception e)
{
Log.e("http", "biffed it getting HTTPResponse");
}
finally
{
try {
if (is != null)
is.close();
} catch (Exception e) {}
}
return "";
}
}
Where can I find information to learn how to write the code correctly?
Or do you happen to have the answer in some kind of hint so I can learn from it?
You must create a BufferedReader passing the InputStream, then you can read strings
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
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();
}
Then I recommend you make the connection (or read/write file) with a separeted thread from the Thread UI (use Thread, AsyncTask, Handler, etc) because that will improve your app.
http://developer.android.com/intl/es/guide/components/processes-and-threads.html
I'm trying to launch first app that handles Http requests. The following code is from a tutorial book and it doesn't work:
package com.example.httpgetdemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BufferedReader in = null;
System.out.println("Before");
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://google.com/");
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
System.out.println(page);
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
What do I mean by saying it doesn't work - I run in it on a phone and LogCat shows the first System.out.println but not the second one, there is error saying:
E/(1755): Can't open file for reading
I read some threads over here about making it in asynchronous way, but if so, then the app would crash and, what-more, it's a book example so it should work, shouldn't it? The aim phone runs the ICS
What's wrong?
Thanks
package com.callout.project;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import com.callout.project.Mylocation.LocationResult;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class WorksActivity extends Activity {
/** Called when the activity is first created. */
Mylocation myLocation = new Mylocation();
TextView rtv;
String id;
String strloc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
Bundle ext = getIntent().getExtras();
id = (String) ext.get("registration_id");
Log.w("rid", id);
findCurrentLocation();
rtv = (TextView)findViewById(R.id.rtv);
rtv.setText("Thank you For Registering");
String eol = System.getProperty("line.separator");
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(
openFileInput("myfile")));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = input.readLine()) != null) {
buffer.append(line + eol);
Log.w("Hello","123"+line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Log.w("file","msg"+line);
// sendtoserver(id,strloc);
}
private void findCurrentLocation() {
myLocation.getLocation(this, locationResult);
}
public LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
// TODO Auto-generated method stub
if (location != null) {
strloc = location.getLatitude() + ","
+ location.getLongitude();
Log.w("works",strloc);
// TODO Auto-generated method stub
AlertDialog malert = new AlertDialog.Builder(WorksActivity.this).create();
malert.setTitle("here"+strloc);
Log.w("func","in func"+id);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.funnystrippers.co.cc/test.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("Rid", "56"));
nameValuePairs.add(new BasicNameValuePair("location","strloc"));
nameValuePairs.add(new BasicNameValuePair("content", "hello frm android"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.w("res",response.toString());
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
malert.show();
}
}
};
}
I have this following code which deals with the C2DM, its working fine , but i want the value of Log.w("Hello","123"+line); to be printed outside the try {}
catch block when I do so it gives me error I should get the value printed in my LogCat !!!
line goes out of scope once you leave the try block since it's declared inside of it.
To fix it just move the declaration of line outside the try block and it will still be visible once you leave the block.
String line;
try {
input = new BufferedReader(new InputStreamReader(
openFileInput("myfile")));
StringBuffer buffer = new StringBuffer();