Populating text fields on a website from android without showing a WebView - java

Is there a way to put values into text fields on a webpage from android without loading/showing a WebView? For example, I have two strings and would like to populate two fields on a webpage, is there a way to do this "in the background" or in other words, not having to open a window that the user sees?
Thanks
Update
Found a solution with the help of Tango
This is in my OkHttpHandler class:
public class OkHttpHandler extends AsyncTask<String, Void, String> {
OkHttpClient client = new OkHttpClient();
String cardNumber, privNumber;
public OkHttpHandler(String cardNumber, String privNumber) {
this.cardNumber = cardNumber;
this.privNumber = privNumber;
}
#Override
protected String doInBackground(String... strings) {
RequestBody formBody = new FormBody.Builder()
//Change .add first parameter to the text field you want to populate
.add("CardNbr", cardNumber)
.add("CardPin", privNumber).build();
Request request = new Request.Builder().url(strings[0])
.post(formBody).build();
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful())
throw new IOException("Unexpected code "+ request.toString());
return response.body().string();
} catch (Exception e) {
}
return null;
}
}
A snippet of my MainActivity Class and I print the response to the Log
OkHttpHandler handler = new OkHttpHandler(items.get(0).getNumber(), items.get(0).getPrivNumber());
String result = "";
try {
result = handler.execute("urlHere.com").get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.d("returned value", result);

Using OkHttp
final OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("field to be filled", "content")
.build();
Request request = new Request.Builder()
.url("webpage url")
.post(formBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

Related

Error while sending data with POST request in Android

I always get the same error while sending username and password to server. I need to send data as content type:form-data, because server isn't responding on any other type. I tested in postman and it's ok, but when I am trying to send it in code, it's not working. Can someone help me, thanks!!
public class Login extends AsyncTask<String, Void, Void> {
String userName;
String password;
public Login(String user, String pass) {
userName = user;
password = pass;
}
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(String... params) {
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("user",userName)
.addFormDataPart("pass",password)
.build();
Request request = new Request.Builder()
.url("http://www.autotrack.rs/android_juzna_backa/login.php")
.method("POST", body)
.build();
try {
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
try {
Call call = client.newCall(request);
Response response = call.execute();
System.out.println(response.body().string());
}catch (Exception m)
{
Log.d("Mytag", m.getMessage());
}
if(!response.isSuccessful())
{
try {
throw new IOException("Unexpected: "+response);
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean okhttp3.Response.isSuccessful()' on a null object reference
This code works perfectly fine for me:
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("user","pera")
.addFormDataPart("pass","1111")
.build();
Request request = new Request.Builder()
.url("http://www.autotrack.rs/android_juzna_backa/login.php")
.method("POST", body)
.build();
Response response = client.newCall(request).execute();
In your code I see that you execute the same request twice, maybe this is the issue?

get request is not working on android device however it's working on my pc

I've wrote this simple get request
OkHttpClient httpClient = new OkHttpClient();
StringBuilder url = new StringBuilder(serverURL);
String result = "init";
if(params!=null && params.size()!=0){
url = url.append("?"+prepareParam(params));
}
Request request = new Request.Builder().url(url.toString()).build();
Response response = null;
try {
response = httpClient.newCall(request).execute();
result = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}finally {
response.close();
}
when i tested it on my pc it worked just fine however when i tested it on my mobile it gave me the following exception
java.lang.NullPointerException: Attempt to invoke virtual method 'void okhttp3.Response.close()' on a null object reference
try{
response.close();
}
catch(NullPointerException e){
e.printStackTrace();
}
inside finally block.
Try this out rather then using this many try catch.
OkHttpClient client = new OkHttpClient();
String doGetRequest(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
Then just call above method and pass your url whenever you need.
String response =doGetRequest(yourUrl);

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 send push notification by serverside using jUnit testing

I am using this code for sending push notification in Android devices. http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/ Its work. But they are using php in server side. and My Server side is JAVA. so I am trying to create jUnit testing for that. so my server will send push notification. But i have not idea about that. I tried by post method but did not work. getting 401 error.
String regID = "";
pairs.add(new BasicNameValuePair("registration_ids",regID));
pairs.add(new BasicNameValuePair("data","test"));
pairs.add(new BasicNameValuePair("key","my key"));
String url = "https://android.googleapis.com/gcm/send";
String data = makePostCall(url, pairs);
Please suggest to me in jUnit.
I was passing incorrect params. It should be header and body. This is way which I used and working nice.
public class SendPushNotification {
public static void main(String[] arg){
PushNotification pushNoti = new PushNotification();
//collect the device_tokens into JSONArray.
// device_tokens is the tokens of user where we needs to send the push Messages.
String id = "APA9******WVWA";
JSONArray deviceTokenArray = new JSONArray();
// if you want to send more than one device then you have to
// add more ids into JSONArray by using put method.
deviceTokenArray.put(id);
try {
pushNoti.sentPushIntoAndroid(deviceTokenArray, "I Love to my sister and sending a push message in Android Device");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and that is another class which is using HTTPHeader and HTTPBody.
public class PushNotification {
public void sentPushIntoAndroid(JSONArray device_token, String message)
throws JSONException {
HttpPost httppost = new HttpPost("https://android.googleapis.com/gcm/send");
StringEntity stringentity = new StringEntity(generateJSONBodyForHTTPBody(device_token, message).toString(), "UTF-8");
httppost.addHeader("Content-Type", "application/json");
httppost.addHeader("Authorization", "key=AI**********Mo"");
httppost.setEntity(stringentity);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String strresponse = null;
if (entity != null) {
strresponse = EntityUtils.toString(entity);
displayLog("HTTP Response ", strresponse);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private JSONObject generateJSONBodyForHTTPBody(JSONArray device_token, String message) throws JSONException {
JSONObject jObj = new JSONObject();
jObj.put(CommonUtilities.REGISTRATION_ID, device_token);
JSONObject dataJson = new JSONObject();
//NOTE:- In Client side, you have to retrieve below param by using getBundle().getString("id") like it. so it will retrieve the id and do for other params too like as i did for id.
dataJson.put("id", "testingID");
dataJson.put("type", "testingType");
dataJson.put("imglink", "testingimgLink");
dataJson.put("seolink", "testingseoLink");
dataJson.put("msg", "Lata Bhulli");
jObj.put("data", dataJson);
displayLog("JSONObject", jObj.toString());
return jObj;
}
private void displayLog(String tag, String message) {
System.out.println(tag+" "+message);
}
Note:- If you are getting compile error than you have to use latest HTTP Libraries and used in libs folder then add all in build path.

Pulling page content to string android

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();

Categories