Pulling page content to string android - java

I'm trying to pull a php page to string on android.
The problem is that I can't get the response_str variable outside of the try.
Whatever I'm doing it keep returning null.
The URL return 1 or 0.
this is my code:
public String IsLoggedIn() {
String url_text = "http://klh-dev.com/lehava/lehava/system/isloggedin.php";
String response_str = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url_text.toString());
ResponseHandler<String> responseHandler = new BasicResponseHandler();
response_str = client.execute(request, responseHandler);
}
catch (Exception e) {
}
return response_str;
}
The error I'm getting:
10-31 20:33:27.906: I/chromium(13374): [INFO:CONSOLE(74)] "Uncaught TypeError: Object [object Object] has no method 'n33_scrolly'", source: http://www.klh-dev.com/lehava/lehava/system/js/init.js (74)
Thank you,
Morha13

If you are doing that on the Main Thread then you might be getting NetworkOnMainThreadException.
If that is the case, try moving your code to a background thread like using AsyncTask.
And don't forget the INTERNET permission.
Try this:
new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... voids) {
String url_text = "http://klh-dev.com/lehava/lehava/system/isloggedin.php";
String response_str = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url_text.toString());
ResponseHandler<String> responseHandler = new BasicResponseHandler();
response_str = client.execute(request, responseHandler);
Log.v("Response", response_str);
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute();

Related

Can't seem to get http get parameters sent from my Android app to display on my PHP page

I can't seem to get my PHP page to display the data I have sent using a http client in Android. All I need now is displaying it in PHP which seems to be a challenge, I know I have done something wrong.
Any guidance would be much appreciated. I have tried everything from var_dump($_SERVER) to json_decode to display it in PHP. Is it even possible to display it on a PHP page?
private class Connection extends AsyncTask{
#Override
protected Object doInBackground(Object[] objects){
try{
PostData(R.id.fullscreen_content, 3);
}
catch(IOException exception){
exception.printStackTrace();
}
return null;
}
}
protected void PostData(Integer Question_ID,Integer ResponseChosen_ID) {
URL url = new URL("http://10.0.2.2:443/SwlLogin.php");
HttpURLConnection conn =(HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
HttpClient httpClient = new DefaultHttpClient();
HttpGet post = new HttpGet(conn.getURL().toString());
post.setHeader("Content-type","application/json");
conn.connect();
Date date = new Date();
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd", Locale.UK);
SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss",Locale.UK);
String nowDate = dt.format(date);
String nowTime = time.format(date);
String phpDate = nowDate;
String phpTime = nowTime;
ArrayList<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("Question ID", Question_ID.toString()));
params.add(new BasicNameValuePair("Response_Chosen_ID", ResponseChosen_ID.toString()));
params.add(new BasicNameValuePair("TimestampDate", phpDate));
params.add(new BasicNameValuePair("time", phpTime));
JSONArray array = new JSONArray();
array.put(params);
post.setHeader("postData", params.toString());
post.getParams().setParameter("JSON", params);
HttpParams var = httpClient.getParams();
var.setParameter("GET",params);
HttpResponse response = httpClient.execute(post);
OutputStreamWriter write = new OutputStreamWriter(conn.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuilder builder = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
builder.append(line);
}
Log.d("Response:", builder.toString());
builder.toString();
reader.close();
public void happy_click(View view) throws IOException {
try{
new Connection().execute();
report_success();
}
catch(Exception exception){
messageBox("Response was not successful","Failed to process response" + exception.getMessage());
}
}
you can not run this code on the UI thread or you will get a NetworkRequestOnUIThread exception. you have to do this on a different thread.
try using AsyncTask via
private class Uploader extends AsyncTask<Void,Void,Void>{
protected void doInBackground(){
// do network request here
}
private void onPostExecute(){
// handle UI updates here as is on ui Thread
}
}
or you could look at using OkHTTP library which I recommend highly. to do this download the jar from okHttp. add it to you libs folder then you can do network call like this
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
JSONObject parcel = new JSONObject();
try{
parcel.put("email", emailEdit.getText().toString());
parcel.put("password", passwordEdit.getText().toString());
parcel.put("device", "Android");
parcel.put("hash", "1234");;
}catch (JSONException e ){
e.printStackTrace();
}
RequestBody body = RequestBody.create(JSON, parcel.toString());
Request request = new Request.Builder()
.header("Content-Type", "application/json")
.url("YOURURL")
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
if (null != e) {e.printStackTrace();}
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (null != response && response.message().equals(Constants.KEY_OK)) {
JSONObject serverResponse;
try{
serverResponse = new JSONObject(response.body().string());
if(serverResponse.getBoolean(Constants.KEY_SUCCESS)){
Constants.getInstance().setToken(serverResponse.getString(Constants.KEY_TOKEN));
moveToHomePage();
}else{
showLoginFail();
}
}catch (JSONException e ){
e.printStackTrace();
}
response.body().close();
} else {
showLoginFail();
}
}
});
also make sure you have
<uses-permission android:name="...permision.INTERNET">
in your manifest file

How to connect Clusterpoint database to an android appliaction

I am new to NoSQL database and cloud. I am trying to develop a simple application in android using Clusterpoint (DBAAS). I tried and searched so many possibilities, but it is not quite working.
(new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String result = "";
try {
String requestString = "https://username:password#api-eu" +
".clusterpoint.com/908/users/";
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = null;
HttpPost httpPost = new HttpPost(requestString);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
result = EntityUtils.toString(httpEntity);
} catch (IOException e) {
result = "Error";
e.printStackTrace();
} finally {
Log.v("ClusterResponse", result);
return result;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.v("ClusterResponse", s);
}
}).execute();
In my code i replaced username and password with original values.
I got the connection. I am posting my code so the next person can get it right in a much faster way
My mistakes
- Needed GET instead of POST
- Authorization should be of base64 with NOWRAP , so it won't add "CR" line at the end.
(new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String result = "";
try {
String requestString = "https://api-eu.clusterpoint.com/908/users/";
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(requestString);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
httpget.addHeader("Authorization", "Basic "+Base64.encodeToString
("username:password".getBytes(),Base64.NO_WRAP));
result = httpClient.execute(httpget, responseHandler);
} catch (IOException e) {
result = e.toString();
e.printStackTrace();
} finally {
Log.v("ClusterResponse", "Done");
return result;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getBaseContext(), s, Toast.LENGTH_LONG).show();
Log.v("ClusterResponse", s);
}
}).execute();

Android Java 'A resource was acquired at attached stack trace but never released'

I would like to grab the HTML code of a webpage, and display it in an edittext control, but i end up with this error:
1482-1491/android.process.acore E/StrictMode﹕ A resource was acquired
at attached stack trace but never released. See java.io.Closeable for
information on avoiding resource leaks.
This is my code:
class GetResult implements Runnable {
private volatile String bodyHtml;
#Override
public void run() {
try {
String myUri = "http://www.google.com";
HttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(myUri);
HttpResponse response = httpClient.execute(get);
bodyHtml = EntityUtils.toString(response.getEntity());
//return bodyHtml;
} catch (IOException e) {
bodyHtml = "kapot";
}
}
public String getbodyHtml(){
return bodyHtml;
}
}
and
String rs = "";
GetResult foo = new GetResult();
new Thread(foo).start();
rs = foo.getbodyHtml();
What am i doing wrong?
You need to close httpClient in a finally block. Like so:
public void run() {
HttpClient httpClient = null
try {
String myUri = "http://www.google.com";
httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet(myUri);
HttpResponse response = httpClient.execute(get);
bodyHtml = EntityUtils.toString(response.getEntity());
//return bodyHtml;
} catch (IOException e) {
bodyHtml = "kapot";
} finally {
if (httpClient != null) {
httpClient.close();
}
}
}

Android httpclient login to Rails server

I started to learn about how to make an Android application. I tried to connect my app to rails server by using httpclient, however I cannot understand how to connect between app and the remote server.
Here is part of my code, and I matched id form inside "BasicNameValuePair" with html id values. Please let me know how to check whether login is successful or not.
class SendPost extends AsyncTask<Void, Void, String>
{
protected String doInBackground(Void... unused) {
String content = executeClient();
return content;
}
protected void onPostExecute(String result) {
}
public String executeClient() {
ArrayList<NameValuePair> post = new ArrayList<NameValuePair>();
post.add(new BasicNameValuePair("user_name", "SallyCook"));
post.add(new BasicNameValuePair("user_email", "domain#ppls.kr"));
post.add(new BasicNameValuePair("user_password", "add123456"));
post.add(new BasicNameValuePair("user_password_confirmation", "add123456"));
post.add(new BasicNameValuePair("user_phone", "01013089579"));
HttpClient client = new DefaultHttpClient();
HttpParams params = client.getParams();
System.out.println(params);
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
HttpPost httpPost = new HttpPost("http://www.ppls.kr/users/sign_up");
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(post, "UTF-8");
httpPost.setEntity(entity);
HttpResponse responsePost = client.execute(httpPost);
System.out.println(responsePost.getStatusLine());
HttpEntity resEntity=responsePost.getEntity();
if (resEntity != null) {
Log.w("RESPONSE", EntityUtils.toString(resEntity));
}
return EntityUtils.getContentCharSet(entity);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}

Android: send post that has no response

In my app, I need to send all sorts of POST requests to a server. some of those requests have responses and others don't.
this is the code I'm using to send the requests:
private static final String TAG = "Server";
private static final String PATH = "http://10.0.0.2:8001/data_connection";
private static HttpResponse response = null;
private static StringEntity se = null;
private static HttpClient client;
private static HttpPost post = null;
public static String actionKey = null;
public static JSONObject sendRequest(JSONObject req) {
try {
client = new DefaultHttpClient();
actionKey = req.getString("actionKey");
se = new StringEntity(req.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "application/json"));
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post = new HttpPost(PATH);
post.setEntity(se);
Log.d(TAG, "http request is being sent");
response = client.execute(post);
Log.d(TAG, "http request was sent");
if (response != null) {
InputStream in = response.getEntity().getContent();
String a = convertFromInputStream(in);
in.close();
return new JSONObject(a);
}
} catch (UnsupportedEncodingException e) {
Log.d(TAG, "encoding request to String entity faild!");
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.d(TAG, "executing the http POST didn't work");
e.printStackTrace();
} catch (IOException e) {
Log.d(TAG, "executing the http POST didn't work");
e.printStackTrace();
} catch (JSONException e) {
Log.d(TAG, "no ActionKey");
e.printStackTrace();
}
return null;
}
private static String convertFromInputStream(InputStream in)
throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
return (sb.toString());
}
This is the code for the AsyncTask class that sends the request:
class ServerRequest extends AsyncTask<JSONObject, Void, JSONObject> {
#Override
protected JSONObject doInBackground(JSONObject... params) {
JSONObject req = params[0];
JSONObject response = Server.sendRequest(req);
return response;
}
#Override
protected void onPostExecute(JSONObject result) {
// HANDLE RESULT
super.onPostExecute(result);
}
}
my problem starts when the server doesn't return a response. the AsyncTask thread stays open even after the work is done because the HTTPClient never closes the connection.
Is there a way to not wait for a response? this is something that will definitely add a lot of overhead to the server since all the Android apps trying to connect to it will keep the connection alive, and will probably cause many problems on the app itself.
Basically, what I'm looking for is a method that will allow me to send to POST message and kill the connection right after the sending of the request since there is no response coming my way.
Just, Set ConnectionTimeOut with HttpClient Object, (Code is for your understanding in your case it may be different)
int TIMEOUT_MILLISEC = 30000;
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient httpclient = new DefaultHttpClient(httpParams);
HttpPost httppost = new HttpPost(url);
httppost.addHeader("Content-Type", "application/json");
Now, It will terminate the Connection after TimeoOut you defined. But be sure this will throw TimeOutException so You have to handle this exception in your HttpRequest.. (Use Try -catch)
EDIT: Or you can use HttpRequestExecutor class.
From class HttpRequestExecutor of package org.apache.http.protocol
protected boolean canResponseHaveBody (HttpRequest request, HttpResponse response)
Decide whether a response comes with an entity. The implementation in this class is based on RFC 2616. Unknown methods and response codes are supposed to indicate responses with an entity.
Derived executors can override this method to handle methods and response codes not specified in RFC 2616.

Categories