Check for username availability when creating users in android - java

I am creating my first android which will take data from a signup form and send it to a php backend.
The php backend will take the data and save in a database and give a jason encoded message telling if it is success or not.
Now I want to eliminate the possibility of dupilicate usernames so when the android app sends data to the php backend I will first check and if it is duplicate I will throw an error message like this
$response["error"] = true;
$response["message"] = "Username Already taken";
echoRespnse(400,$response);
On Success the backend will send something like this
$response["error"] = false;
$response["message"] = "Successfuly Registered";
echoRespnse(201,$response);
How do I enable the android app to read this info and understand if the user was created or an error occured.
My current Android signup.java code looks like this
public void post() throws UnsupportedEncodingException
{
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.rgbpallete.in/led/api/signup");
if (password.equals(confirmpass)) {
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("uname", uname));
nameValuePairs.add(new BasicNameValuePair("pass", password));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("phone", phone));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
//Code to check if user was successfully created
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(getBaseContext(), "Password mismatch", Toast.LENGTH_SHORT).show();
//Reset password fields
pass.setText("");
cpass.setText("");
}
}

I think you want help to get and read the JSON data provided by your service, right?
In your SignUp Activity create an AsyncTask because you can not perform this on the main thread.
private class DownloadOperation extends AsyncTask<Void, Void, String> {
String uname = "";
String email = "";
String password = "";
String confirmpass = "";
String phone = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
}
#Override
protected String doInBackground(Void... params) {
String response = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.rgbpallete.in/led/api/signup");
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("uname", uname));
nameValuePairs.add(new BasicNameValuePair("pass", password));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("phone", phone));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
httpResponse = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("tag", "Result:\n" + result);
}}
And then call
// Calling async task to get json
new DownloadOperation().execute();
And you will see the json string printed on your Console :)
To get an JSONObject using the response String:
JSONObject jsonObj = new JSONObject(STRING);
Hope that helps.

You could make your "error" an int instead of a boolean, and have your php backend return specific error codes. This would allow your android application to understand the specific error. Without this kind of modification, checking the value of message for a specific string is another option.
For example, you could return 0 if there was no error, 1 if the username was already taken, 2 if .. etc.

BEFORE registering the user and inserting into database ,check the query for username in database..and if user name found then encode json value as error
$query=mysql_query("select id from yourtable where username ='$username'");
If(mysql_numnum_rows($query)>0)
// example for response
//responses from server for success
response["success"]=1;
response["message"]='No error code'
//responses from server for duplicate username
response["success"]==0
response["message"]='Username exists';
// java code
// after getting string from server parse in into json object
JSONObject jsonObj = new JSONObject(STRING);
int success = jsonObj.getInt("success");
message = jsonObj.getString("message");
if (success == 1) {
// register successfully
} else {
// username already exist
}

Related

How to send JSON raw via POST Request on Android API Level 22

Currently I'am debugging my Java Code as follows:
public void sign_in(View view) {
String json = "";
// The Username & Password
final EditText em = (EditText) findViewById(R.id.Username);
String email = (String) em.getText().toString();
final EditText pw = (EditText) findViewById(R.id.Password);
String password = (String) pw.getText().toString();
// -----------------------
JSONObject jsonObject = new JSONObject();
try {
HttpResponse response;
jsonObject.accumulate("email", email);
jsonObject.accumulate("password", password);
json = jsonObject.toString();
URL url = new URL("http://cloudspecinc.herokuapp.com/api/user/login/");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url.toURI());
httpPost.setEntity(new StringEntity(json, "UTF-8"));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
httpPost.setHeader("Accept-Language", "en-US");
response = httpClient.execute(httpPost);
String sresponse = response.getEntity().toString();
}
catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
} finally {
/* nothing to do here */
}
}
My question:
How can I get the response of the POST Request? It's not yet in the
code because I don't know how to get it.
The severe problem: When i click the "LOG IN" button the app always
crashes. (NOTE: It compiles on android studio but crashes
when I click the "LOG IN" button that trigger the sign in function).
Something that I think the problem is:
HttpClient is deprecated in Android API Level 22. (Android 5.1
Lollipop API Level 22)
Something is wrong with the code.
OK Now I know.. Requesting HTTP Type Request must be on a AsyncTask. not on the current thread because it will throw an exception when not on a Asynchronous Class due to Network Threading Exception. I forgot what the Exception is called. I'am only a beginner on Java. because I'am not really a Java programmer.
Here is the code to help others on this kind of problem.
public class REST extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection=null;
String json = null;
// The Username & Password
final EditText em = (EditText) findViewById(R.id.Username);
String email = (String) em.getText().toString();
final EditText pw = (EditText) findViewById(R.id.Password);
String password = (String) pw.getText().toString();
// -----------------------
try {
HttpResponse response;
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("email", email);
jsonObject.accumulate("password", password);
json = jsonObject.toString();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://cloudspecinc.herokuapp.com/api/user/login/");
httpPost.setEntity(new StringEntity(json, "UTF-8"));
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept-Encoding", "application/json");
httpPost.setHeader("Accept-Language", "en-US");
response = httpClient.execute(httpPost);
String sresponse = response.getEntity().toString();
Log.w("QueingSystem", sresponse);
Log.w("QueingSystem", EntityUtils.toString(response.getEntity()));
}
catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
} finally {
/* nothing to do here */
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (result != null) {
// do something
} else {
// error occured
}
}
}

Android - Display data from MySQL

I'm very new to Android and I'm currently making an application wherein the user can enter and ID number once (that serves as a login) and he can use access the rest of the features of the app.
I'm currently stuck in the displaying of a data from the MySQL server. Using the ID that the user entered (which is unique and only the user's identificaton), I can display the information with of the user (through TextView or something).
This is my code so far:
public class MainActivity3Activity extends Activity {
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
TextView tv;
TextView tv2;
String get;
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity3);
tv = (TextView)findViewById(R.id.tv);
tv2 = (TextView)findViewById(R.id.tv2);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://usamobileapp.pe.hu/webservice/student_info.php");
SharedPreferences preferences = getSharedPreferences("rfid", Context.MODE_PRIVATE);
if(preferences.contains("rfid")){
get = preferences.getString("rfid", null);
}
}
So my question what do I do from here? I'm quite familiar about httpost but I'm wondering how do I display the user information using the previously entered ID during the login? I heard things like JSON parsing but I'm not quite sure on how to use it.
How do I get to display the information of the user matching the ID he entered? How to diplay using a TextView?
Thanks for the help.
PS. Please disregard the webview there. I only used it as a sample if my app really us connected to my php.
1) make a restful API on your server
2) receive API elements on your client (android), i suggest retrofit, its too easy
3) display your data! otto will help :)
want more? more ,
it might seem hard, but if you study for a few days you'll learn it.
To implement a login / registration system using MySql you need a server-side API, for example in PHP to manipulate the database.
You need something like that on the server side:
// check for tag type
if ($tag == 'login') {
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];
// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// user found
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = TRUE;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
And the function that queries the database:
public function getUserByEmailAndPassword($username, $password) {
$query = $this->dbh->prepare("SELECT * FROM users2 WHERE username = :username");
$query->bindParam(':username', $username);
$result = $query->execute();
// check for results
if ($query->rowCount() > 0) {
$result = $query->fetch(PDO::FETCH_ASSOC);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
return $result;
}
} else {
// user not found
return false;
}
}
The android 'calls' the php scripts:
private static String login_tag = "login";
public void loginUser(String username, String password) throws ExecutionException, InterruptedException {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
jsonParser = new DbHandler(activity, this, params).execute();
}
And here is the DbHandler:
public DbHandler1(Activity activity, MyCallback dbIntf, List<NameValuePair> params) {
this.activity = activity;
intf = dbIntf;
this.params = params;
}
public JSONObject makeHttpRequest() {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(MainActivity.baseUrl);
//If database contains greek characters instantiate with UTF-8 Encoding
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (HttpHostConnectException e) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(activity, R.string.connection_error, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
}
try {
//If database contains greek characters instantiate with UTF-8 Encoding
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
#Override
protected JSONObject doInBackground(Void... params) {
jObj = makeHttpRequest();
return jObj;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
try {
intf.onRemoteCallComplete(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
So the php scripts 'catches' the tag and if the user exists it returns a JSON response to the device. For example:
{
"tag": "login",
"success": 1,
"error": 0,
}
The data transfered from the MySql server must be JSON encoded.
On the android device you must read the JSON Response and act accordingly.
Take a look here for more details.
login / registration system
json parsing
you need perform network operations on a separate thread from the UI.
reade aboute rest Google I/O 2010 - Developing Android REST client application
documentation
in the client, for rest api i like use retrofit + gsongroundy
or php, very easy create rest api using slim framework ─ How to create REST API for Android app using PHP, Slim and MySQL

Cannot send data from Android application to remote database

I want to send registration form data from android application to remote MySQL database but every time I get same error:
java.lang.String can not be converted to JSONObject.
Here is my code:
JSONParser.java
`public class JSONParser
{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) throws JSONException
{
try
{
// check for request method
if(method == "POST")
{
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
else if(method == "GET")
{
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}
catch (Exception e)
{
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try
{
jObj = new JSONObject(json);
}
catch (JSONException e)
{
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return new JSONObject(json.substring(json.indexOf("{"),json.lastIndexOf("}") + 1));
}
}
`
and here is my mainActivity code
class submitForm extends AsyncTask<String, String, String>
{
#Override
protected String doInBackground(String... args)
{
try
{
String first_name = mFirstname.getText().toString();
String last_name = mLastname.getText().toString();
String username = mUsername.getText().toString();
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
String mobile = mMobile.getText().toString();
String country = mCountry.getSelectedItem().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("FirstName", first_name));
params.add(new BasicNameValuePair("LastName", last_name));
params.add(new BasicNameValuePair("Username", username));
params.add(new BasicNameValuePair("Email", email));
params.add(new BasicNameValuePair("Password", password));
params.add(new BasicNameValuePair("Mobile", mobile));
params.add(new BasicNameValuePair("Country", country));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(
url_create_product, "POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// finish();
} else {
// failed to create product
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), " in catch",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
catch (Exception ex) {
Log.e("DIG", ex.toString());
}
return null;
}
}
this is my php file
<?php
// array for JSON response
header('Content-type=application/json; charset=utf-8');
$response = array();
$fname = $_POST['Firstname'];
$lname = $_POST['Lastname'];
$uname = $_POST['Username'];
$email = $_POST['Email'];
$password = $_POST['Password'];
$country = $_POST['Country'];
$mobile = $_POST['Mobile'];
// include db connect class
require_once ('db_connect.php');
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysqli_query("INSERT INTO users(Firstname,Lastname,Username,Email,Password,Country,Mobile) VALUES('$fname', '$lname', '$uname', '$email', '$password', '$country', '$mobile')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "User inserted successfully.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
?>
on server side i get the error
undefined index Firstname,Lastname,username,Email,Password...
and in eclipse logcat i get error
java.lang.string can not be converted to JSONObject
You can't access that data in php through POST because it is being sent on the android application through the HTTP header and not over application/x-www-form-urlencoded.
Here's a thread that explains how you can do it:
How to retrieve Request Payload

HttpPost send GET to the server

Problem on my part is solved
The owner of the server removed some code to check if the basics of sending a POST/GET method works and that works perfectly.
I'm still dont know what the problem is, but it sure is not my problem lol
I'm trying to send POST method to the server, but it turns out the server gets a GET method instead. We got it working on the iphone so the server is correct.
This is the code I written to send data:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myurl.nl/casus");
httppost.setHeader("Authorization", "xxxxxxxxxxxxxxx");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
//casus
nameValuePairs.add(new BasicNameValuePair("casusid", casus.id+""));
String woorden = "[";
for(int i = 0; i < words.length; i++){
woorden += "\""+words[i]+"\"";
if(i != words.length-1){
woorden += ",";
}
}
woorden += "]";
nameValuePairs.add(new BasicNameValuePair("woorden", woorden));
//info
SharedPreferences sharedPref = getSharedPreferences("omapp", MODE_PRIVATE);
String age = sharedPref.getString("age", "");
String sex = sharedPref.getString("sex", "");
nameValuePairs.add(new BasicNameValuePair("leeftijdscategorie", age));
nameValuePairs.add(new BasicNameValuePair("geslacht", sex));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.d("json", responseBody);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
PHP code:
// Service token authorization.
require_once('../classlib/Auth.php');
$auth = new Auth;
if ( !$auth->valid() ) {
header('HTTP/1.1 401 Unauthorized');
exit;
}
// Setup casussen.
require_once('../classlib/PDOFactory.php');
require_once('../classlib/Casussen.php');
$casussen = new Casussen;
$casussen->setPDO(PDOFactory::create());
$rs = (object) array();
switch ( $_SERVER['REQUEST_METHOD'] ) {
case 'GET': {
mail('sdgsdgsdg#gmail.com', 'The get method was called', print_r($_SERVER,1));
$fromcasusid = !empty($_GET['fromcasusid']) ? (int) $_GET['fromcasusid'] : null;
$rs->casussen =$casussen->get($fromcasusid);
break;
}
case 'POST': {
mail('jsdgsdgsn#gmail.com', 'The post method was called', print_r($_SERVER,1));
$casusreactie = json_decode(file_get_contents("php://input"));
try {
$casussen->post($casusreactie);
} catch ( Exception $e ) {
$rs->error = (object) array(
'code' => $e->getCode(),
'message' => $e->getMessage(),
);
}
break;
}
default: {
header('HTTP/1.1 405 Method Not Allowed');
exit;
}
} // switch
header('Content-type: application/json; charset=utf-8');
exit(json_encode($rs));
One workout..
call doPost method from inside your doGet
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException{
doPOst(request, response)
}
I was also having a similar issues.
I was able to fix it by add "www." to the url.
But i would like to know how that is making a difference, I had successfully tested the server handling with a jQuery ajax request without the "www." .

recieving HTTP POST echo response from a PHP file (sending the POSTS works fine, it's the receive that I can't figure out)

So as the title suggest my problem is getting a response to a HTTP POST I'm making.
What SHOULD be happening is I send a bunch of variables, the PHP checks the database for them and sends back to me the result (as an echo to the page).
Here is the android code:
public class CheckChallenge extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls)
{
String response = "";
try
{
URL = urls[0];
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("victim",NetPlay.myId));
// need to return these to an array
nameValuePairs.add(new BasicNameValuePair("rival",rivalid));
nameValuePairs.add(new BasicNameValuePair("word","null"));
nameValuePairs.add(new BasicNameValuePair("won","0"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://www.hanged.comli.com/check-rival.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse execute = httpclient.execute(httppost);
HttpEntity entity = execute.getEntity();
//InputStream is = entity.getContent();
//mText.setText(is.toString());
Log.i("postData", execute.getStatusLine().toString());
//HttpEntity entity = response.getEntity();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
}
return response;
}
#Override
protected void onPostExecute(String result)
{
// CHECK ENTIRE DATABASE FOR MY ID //
// IF MY ID IS THERE THEN THAT MEANS IVE CHALLENGED SOMEONE //
}
}
Here is the PHP which I think is ok just including this for completeness:
$connect = mysql_connect("$mysql_host", "$mysql_user", "$mysql_password")or die("cannot connect");
mysql_select_db("$mysql_database", $connect)or die("cannot select DB");
session_start();
$victim = $_POST['victim'];
$rival = $_POST['rival'];
$word = $_POST['word'];
$won = $_POST['won'];
$query = "SELECT rival FROM currentgames";
$result = mysql_query($query);
if (!$result)
{
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0)
{
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result))
{
echo $row["rival"];
}
Any help with this would be very appreciated, trying to get my head around all this HTTP POSTing stuff.
Example of sending an HTTP request and reading back the HTTP response:
String res = "";
String url = "http://www.domain.com/youscript.php";
URL urlObj = new URL(url);
URLConnection lu = urlObj.openConnection();
// Send data - if you don't need to send data
// ignore this section and just move on to the next one
String data = URLEncoder.encode("yourdata", "UTF-8");
lu.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(lu.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(lu.getInputStream()));
String line = "", res = "";
while ((line = rd.readLine()) != null) {
res += line;
}
wr.flush();
wr.close();
System.out.println(res);

Categories