I am fairly new to Android Dev and I created a Google Form and wanted to implement the form on my app and I heard about the open source okhttp from Square Open Source, which you most likely know
So, I created a layout with the labels, gave them the same IDs and everything...
I created a java class called Form and inserted all the code, and no errors whatsoever.
(Worth mentioning I am using navigation drawer activity, don't know if that influences or not though)
So after implementing and correcting everything there was to correct, I ran the application but it just doesnt do anything. It does not do the validation nor it sends the response.
I would really appreciate if anyone could help me out with this
I will leave the code here
Once again, thanks.
package com.example.eduardobastos.testapp;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class Form extends AppCompatActivity {
public static final MediaType FORM_DATA_TYPE
= MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
//URL derived from form URL
public static final String URL="https://docs.google.com/forms/d/e/1FAIpQLSeZp9wjprZJ3OR2SkIHHsZE9yDBAVnC7mO8hPKSzwGuYhqmdw/formResponse";
//input element ids found from the live form page
public static final String EMAIL_KEY="entry_943499687";
public static final String SUBJECT_KEY="entry_2058392291";
public static final String MESSAGE_KEY="entry_1420026128";
private Context context;
private EditText emailEditText;
private EditText subjectEditText;
private EditText messageEditText;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.form_layout);
//save the activity in a context variable to be used afterwards
context =this;
//Get references to UI elements in the layout
Button sendButton = (Button)findViewById(R.id.sendButton);
emailEditText = (EditText)findViewById(R.id.emailEditText);
subjectEditText = (EditText)findViewById(R.id.subjectEditText);
messageEditText = (EditText)findViewById(R.id.messageEditText);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Make sure all the fields are filled with values
if(TextUtils.isEmpty(emailEditText.getText().toString()) ||
TextUtils.isEmpty(subjectEditText.getText().toString()) ||
TextUtils.isEmpty(messageEditText.getText().toString()))
{
Toast.makeText(context,"All fields are mandatory.",Toast.LENGTH_LONG).show();
return;
}
//Check if a valid email is entered
if(!android.util.Patterns.EMAIL_ADDRESS.matcher(emailEditText.getText().toString()).matches())
{
Toast.makeText(context,"Please enter a valid email.",Toast.LENGTH_LONG).show();
return;
}
//Create an object for PostDataTask AsyncTask
PostDataTask postDataTask = new PostDataTask();
//execute asynctask
postDataTask.execute(URL,emailEditText.getText().toString(),
subjectEditText.getText().toString(),
messageEditText.getText().toString());
}
});
}
//AsyncTask to send data as a http POST request
private class PostDataTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... contactData) {
Boolean result = true;
String url = contactData[0];
String email = contactData[1];
String subject = contactData[2];
String message = contactData[3];
String postBody="";
try {
//all values must be URL encoded to make sure that special characters like & | ",etc.
//do not cause problems
postBody = EMAIL_KEY+"=" + URLEncoder.encode(email,"UTF-8") +
"&" + SUBJECT_KEY + "=" + URLEncoder.encode(subject,"UTF-8") +
"&" + MESSAGE_KEY + "=" + URLEncoder.encode(message,"UTF-8");
} catch (UnsupportedEncodingException ex) {
result=false;
}
try{
//Create OkHttpClient for sending request
OkHttpClient client = new OkHttpClient();
//Create the request body with the help of Media Type
RequestBody body = RequestBody.create(FORM_DATA_TYPE, postBody);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
//Send the request
Response response = client.newCall(request).execute();
}catch (IOException exception){
result=false;
}
return result;
}
#Override
protected void onPostExecute(Boolean result){
//Print Success or failure message accordingly
Toast.makeText(context,result?"Message successfully sent!":"There was some error in sending message. Please try again after some time.",Toast.LENGTH_LONG).show();
}
}
}
Just tested this, and works like a charm...
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import butterknife.BindView;
import butterknife.ButterKnife;
import mx.com.iisi.staffing.R;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MessageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
protected void onResume() {
super.onResume();
new PostDataTask(this).execute("","testing#testing.com","Testing","Testing message");
}
private class PostDataTask extends AsyncTask<String, Void, Boolean> {
public final MediaType FORM_DATA_TYPE
= MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
//URL derived from form URL
public static final String URL="https://docs.google.com/forms/d/e/1FAIpQLSeZp9wjprZJ3OR2SkIHHsZE9yDBAVnC7mO8hPKSzwGuYhqmdw/formResponse";
//input element ids found from the live form page
public static final String EMAIL_KEY="entry_943499687";
public static final String SUBJECT_KEY="entry_2058392291";
public static final String MESSAGE_KEY="entry_1420026128";
private Context context;
public PostDataTask(Context context)
{
this.context = context;
}
#Override
protected Boolean doInBackground(String... contactData) {
Boolean result = true;
String url = contactData[0];
String email = contactData[1];
String subject = contactData[2];
String message = contactData[3];
String postBody="";
try {
//all values must be URL encoded to make sure that special characters like & | ",etc.
//do not cause problems
postBody = EMAIL_KEY+"=" + URLEncoder.encode(email,"UTF-8") +
"&" + SUBJECT_KEY + "=" + URLEncoder.encode(subject,"UTF-8") +
"&" + MESSAGE_KEY + "=" + URLEncoder.encode(message,"UTF-8");
} catch (UnsupportedEncodingException ex) {
result=false;
}
try{
//Create OkHttpClient for sending request
OkHttpClient client = new OkHttpClient();
//Create the request body with the help of Media Type
RequestBody body = RequestBody.create(FORM_DATA_TYPE, postBody);
Request request = new Request.Builder()
.url(URL)
.post(body)
.build();
//Send the request
Response response = client.newCall(request).execute();
}catch (IOException exception){
result=false;
}
return result;
}
#Override
protected void onPostExecute(Boolean result){
Toast.makeText(context,result?"Message successfully sent!":"There was some error in sending message. Please try again after some time.",Toast.LENGTH_LONG).show();
}
}
}
Related
Trying to use the Oauth authorization flow in an andoid app using java. No browser opened needed for authorizing. I don't know if i should ask here or on the api's website
permission for internet is granted in manifest.xml
MainActivity.java:
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button RankConfirm = findViewById(R.id.UsernameConfirm);
RankConfirm.setOnClickListener(v -> {
final EditText username_box = findViewById(R.id.OsuUsername);
final String Username = username_box.getText().toString();
final TextView RankView = findViewById(R.id.RankView);
API_Response.UpdateRank(Username,RankView);
});}
}
API.java
import android.util.Log;
import android.widget.TextView;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class API {
public static void UpdateRank(String Username, TextView RankView) {
Thread NetworkThread = new Thread ("NetworkThread"){
private volatile String Rank = "nic";
public void run() {
OkHttpClient client1 = new OkHttpClient();
Request request1 = new Request.Builder()
.url("https://osu.ppy.sh/oauth/authorize/?client_id=14403&redirect_uri=https://google.com&response_type=code&scope=public")
.build();
try {
Response response1 = client1.newCall(request1).execute();
String Code = response1.body().string();
Log.e("Debug", Code);
} catch (IOException e) {
Log.e("Debug", "IO exception1");
}```
Realized i was doing it completly wrong and i should have used a WebView
My application is passing two value from device to remote server but it work in when i tested in bluestack when I install in real device it show a message like "Unfortunately app has been stooped" so I can't under stand where is problem i delete and clean device temporary and cache memory of device still not getting output.
following is my source code
package com.androidexample.httpgetexample;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class HttpGetAndroidExample extends Activity {
TextView content;
EditText fname,email,login,pass;
Spinner sp;
Button b1;
String s[] = { "Courtage Problem", "Cartage Refil", "Printer Problem",
"Printer Drivers" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_get_android_example);
content = (TextView)findViewById(R.id.content);
fname = (EditText)findViewById(R.id.name);
sp = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> ad = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, s);
sp.setAdapter(ad);
ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Button saveme=(Button)findViewById(R.id.save);
saveme.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v)
{
//ALERT MESSAGE
Toast.makeText(getBaseContext(),
"Please wait, connecting to server.",
Toast.LENGTH_LONG).show();
try{
String n = URLEncoder.encode(fname.getText().toString(), "UTF-8");
String d = URLEncoder.encode(sp.getSelectedItem().toString(), "UTF-8");
HttpClient Client = new DefaultHttpClient();
String URL = "http://shreebijapur.in/Customerquery.aspx?n="+n+"&d="+d;
//Log.i("httpget", URL);
try
{
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String SetServerString = "";
SetServerString = Client.execute(httpget, responseHandler);
content.setText(SetServerString);
}
catch(Exception ex)
{
content.setText("Fail!");
}
}
catch(UnsupportedEncodingException ex)
{
content.setText("Fail111");
}
}
});
}
}
It's probably crashing due to the networkOnMainThreadException. I'm trying to executr an http request in an inner class that extends class AsyncTask.
I put all network related stuff in the doInBackground() method.
If Error: networkOnMainThreadException
Perform http request execution in an inner class that extends the class AsyncTask.
or
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// HERE_YOUR_HTTP_REQUEST CODE
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}.execute();
Try this
Or
You can use volley, retrofit or other networking library's for API call.
I have to retrieve json object from json file from this url.
My code is throwing java.lang.RuntimeException in doInBackground() and string to jsonObject conversion exception.
Can anyone help me at this? I am new to Android programming.
package course.examples.networkingearthquake;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.AsyncTask;
import android.widget.Button;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.net.http.AndroidHttpClient;
public class HttpActivity extends ActionBarActivity {
TextView mTextView;
EditText etInput;
TextView input;
String number;//edited
int num;//edited
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket);
mTextView = (TextView)findViewById(R.id.text1);
input = (TextView)findViewById(R.id.input);
etInput = (EditText)findViewById(R.id.etInput);
input.setText("Input");
//number = etInput.getText().toS();
final Button btDisplay = (Button)findViewById(R.id.btDisplay);
btDisplay.setText("DISPLAY");
btDisplay.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
new HttpGetTask().execute();
}
});
}
private class HttpGetTask extends AsyncTask<Void, Void, String>{
private static final String TAG = "HttpGetTask";
private static final String URL = "http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week";
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected String doInBackground(Void... params){
HttpGet request = new HttpGet(URL);
JSONResponseHandler responseHandler = new JSONResponseHandler();
// ResponseHandler<String> responseHandler = new BasicResponseHandler();
try{
return mClient.execute(request,responseHandler);
}catch(ClientProtocolException exception){
exception.printStackTrace();
}catch(IOException exception){
exception.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
if(null != mClient)
mClient.close();
mTextView.setText(result);
}
}
private class JSONResponseHandler implements ResponseHandler<String>{
#Override
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
String result = null;
String JSONResponse = new BasicResponseHandler().handleResponse(response);
JSONResponse = JSONResponse.substring(17, JSONResponse.length()-3);
num = Integer.parseInt(number);// edited
try {
JSONObject responseObject = (JSONObject) new JSONTokener(
JSONResponse).nextValue();
JSONArray features = responseObject.getJSONArray("features");
JSONObject retObject = (JSONObject)features.get(num);//edited
// JSONObject geometry = (JSONObject)retObject.get("geometry");
result = retObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
}
The JSON returned by the URL you specify containts eqfeed_callback() which needs to be stripped in order to make it valid JSON.
It seems like you have done this in your response handler, but you are cutting off one character too much at both the start and the end.
Try this:
JSONResponse = JSONResponse.substring(16, JSONResponse.length()-2);
after searching around im able to retreive a response from my servlet , but i cant send a parameter (a username and a password parameter) from android to a servlet! My logcat shows this error:
04-0java.lang.ClassCastException: org.apache.http.client.methods.HttpGet cannot be cast to org.apache.http.HttpResponse
at com.example.httpgetandroidexample.MainActivity$AsyncTaskRunner.doInBackground(MainActivity.java:76)
at com.example.httpgetandroidexample.MainActivity$AsyncTaskRunner.doInBackground(MainActivity.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
and i cant understand why!
Here it is my android main activity:
package com.example.httpgetandroidexample;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public TextView content;
EditText name,pass;
String URL,nameValue,passValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.name);
pass = (EditText)findViewById(R.id.pass);
content = (TextView)findViewById(R.id.text);
Button button=(Button)findViewById(R.id.but);
try {
nameValue =URLEncoder.encode(name.getText().toString(), "UTF-8");
passValue =URLEncoder.encode(pass.getText().toString(), "UTF-8");
URL = "http://10.0.2.2:8080/login/web";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute(new String[ ] { URL });
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
List<NameValuePair> postParameters =
new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("user",nameValue));
postParameters.add(new BasicNameValuePair("pass",passValue));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
postParameters);
((HttpResponse) httpGet).setEntity(formEntity);
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
content.setText(result);
}
}
}
Does anyone have any idea?
UPDATE:
now i have changed my android code like this:
package com.example.httpgetandroidexample;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public TextView content;
EditText name,pass;
String URL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.name);
pass = (EditText)findViewById(R.id.pass);
content = (TextView)findViewById(R.id.text);
Button button=(Button)findViewById(R.id.but);
try {
String nameValue ="user="+URLEncoder.encode(name.getText().toString(), "UTF-8");
String passValue ="&pass="+URLEncoder.encode(pass.getText().toString(), "UTF-8");
URL = "http://10.0.2.2:8080/login/web?"+nameValue+passValue;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute(new String[ ] { URL });
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
content.setText(result);
}
}
}
this time runs without logcat errors but the parameters does not come to the servlet!
Looking at the stack trace, I guess your problem is at this line.
((HttpResponse) httpGet).setEntity(formEntity);
Why are you casting it to HttpResponse?
OK. You want to send user/pass parameters using HTTP GET. For HTTP GET, all parameters are part of the URL. Maybe this can give you some help on how to perform a HTTP GET and pass parameters in. But in general, URL would look like this
http://www.blah.com/servlet?user="1234"&pass="password"
The stuff after the ? in the URL contains all the parameters. But there is a length limit in the URL, if you exceed that length, you'll have to use HTTP POST.
Try this link to see if it can help you
http://androidexample.com/How_To_Make_HTTP_Get_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=63&aaid=88
i have modified the activity and the problem was that the URL and nameValue and passValue was declared on the wrong section of the code ! Here it is the right android code:
package com.example.httpgetandroidexample;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public TextView content;
EditText name,pass;
String URL,nameValue,passValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText)findViewById(R.id.name);
pass = (EditText)findViewById(R.id.pass);
content = (TextView)findViewById(R.id.text);
content.setText("Vendosni Perdoruesin dhe Fjalekalimin");
Button button=(Button)findViewById(R.id.but);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nameValue="&user="+name.getText().toString();
passValue ="&pass="+pass.getText().toString();
URL = "http://10.0.2.2:8080/login/web2?activitetiNR=1"+nameValue+passValue;
AsyncTaskRunner runner = new AsyncTaskRunner();
Log.i("url",URL);
Log.i("url",nameValue);
Log.i("url",passValue);
runner.execute(new String[ ] { URL });
}
});
}
private class AsyncTaskRunner extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
content.setText(result);
}
}
}
I am trying to get an Android device to send some HTTP request using GET method.
Here is my code:
package com.kde.httprequest;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class main2 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText edit1 = (EditText) findViewById (R.id.editText1);
Button btn1 = (Button) findViewById (R.id.button1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
grabURL(edit1.getText().toString());
}
});
}
public void grabURL(String url) {
new GrabURL().execute(url);
}
private class GrabURL extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(main2.this);
final TextView text1 = (TextView) findViewById (R.id.textView1);
protected void onPreExecute() {
Dialog.setMessage("Downloading source..");
Dialog.show();
}
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
Dialog.dismiss();
if (Error != null) {
Toast.makeText(main2.this, Error, Toast.LENGTH_LONG).show();
text1.setText(Error);
} else {
Toast.makeText(main2.this, "Source: " + Content, Toast.LENGTH_LONG).show();
text1.setText(Content);
}
}
}
}
My simple PHP test:
<?php
$a = $_GET['user'];
$b = $_GET['pass'];
if ($a=="usr" && $b=="pass") {
echo "success";
} else {
echo "fail";
}
?>
My code is running smoothly when send to this URL:
digitalzone-btm.com/test2.php?user=user&pass=pass
The response from my PHP is a string say "success" or "fail", that is what I am expected.
But I am getting a different response from my local webserver with a same Android app and PHP file.
Ex url:
http://192.168.1.8/test2.php?user=user&pass=pass
The response is exactly my PHP source code.
How can I get a "success" or "fail" response from my local webserver?
It would appear your local web server doesn't have php installed or configured right. Check here for help.
PHP: Installation and Configuration - Manual