简体   繁体   English

Android,从应用程序发送字符串到Web服务器

[英]Android, send string from app to web server

I am trying to make an app where i am supposed to send data from the application to a web server. 我正在尝试创建一个应用程序,我应该将数据从应用程序发送到Web服务器。 So far i've been searching and not been able to find a working example, i've found some using asynctask which does not work, so any help is appreciated! 到目前为止,我一直在搜索,但未能找到一个有效的例子,我发现一些使用asynctask不起作用,所以任何帮助表示赞赏!

try below code :- 尝试以下代码: -

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.hmkcode.android.vo.Person;

public class MainActivity extends Activity implements OnClickListener {

    TextView tvIsConnected;
    EditText etName,etCountry,etTwitter;
    Button btnPost;

    Person person;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // get reference to the views
        tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
        etName = (EditText) findViewById(R.id.etName);
        etCountry = (EditText) findViewById(R.id.etCountry);
        etTwitter = (EditText) findViewById(R.id.etTwitter);
        btnPost = (Button) findViewById(R.id.btnPost);

        // check if you are connected or not
        if(isConnected()){
            tvIsConnected.setBackgroundColor(0xFF00CC00);
            tvIsConnected.setText("You are conncted");
        }
        else{
            tvIsConnected.setText("You are NOT conncted");
        }

        // add click listener to Button "POST"
        btnPost.setOnClickListener(this);

    }

    public static String POST(String url, Person person){
        InputStream inputStream = null;
        String result = "";
        try {

            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();

            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);

            String json = "";

            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("name", person.getName());
            jsonObject.accumulate("country", person.getCountry());
            jsonObject.accumulate("twitter", person.getTwitter());

            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();

            // ** Alternative way to convert Person object to JSON string usin Jackson Lib 
            // ObjectMapper mapper = new ObjectMapper();
            // json = mapper.writeValueAsString(person); 

            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);

            // 6. set httpPost Entity
            httpPost.setEntity(se);

            // 7. Set some headers to inform server about the type of the content   
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            // 8. Execute POST request to the given URL
            HttpResponse httpResponse = httpclient.execute(httpPost);

            // 9. receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

            // 10. convert inputstream to string
            if(inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        // 11. return result
        return result;
    }

    public boolean isConnected(){
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isConnected()) 
                return true;
            else
                return false;    
    }
    @Override
    public void onClick(View view) {

        switch(view.getId()){
            case R.id.btnPost:
                if(!validate())
                    Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
                // call AsynTask to perform network operation on separate thread
                new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
            break;
        }

    }
    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

            person = new Person();
            person.setName(etName.getText().toString());
            person.setCountry(etCountry.getText().toString());
            person.setTwitter(etTwitter.getText().toString());

            return POST(urls[0],person);
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
       }
    }

    private boolean validate(){
        if(etName.getText().toString().trim().equals(""))
            return false;
        else if(etCountry.getText().toString().trim().equals(""))
            return false;
        else if(etTwitter.getText().toString().trim().equals(""))
            return false;
        else
            return true;    
    }
    private static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }   
}

see below link for more info :- 请参阅以下链接了解更多信息: -

http://hmkcode.com/android-send-json-data-to-server/ http://hmkcode.com/android-send-json-data-to-server/

http://androidexample.com/How_To_Make_HTTP_POST_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=64&aaid=89 http://androidexample.com/How_To_Make_HTTP_POST_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=64&aaid=89

Try this, 尝试这个,

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class AdminLogin extends Activity {

    EditText adminUN, adminPass;
    CheckBox cb;
    Button loginBtn;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    List<NameValuePair> nameValuePairs;

   // Your IP address or your website complete address
    String adminLoginURL = "http://192.168.1.1/admin_login.php";
    ProgressDialog dialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.admin_login);

        loginBtn = (Button) findViewById(R.id.adminLogin);
        adminUN = (EditText) findViewById(R.id.adminUName);
        adminPass = (EditText) findViewById(R.id.adminPass);

        loginBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                new Admin_Login().execute();

            }
        });
    }

    class Admin_Login extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(AdminLogin.this);
            dialog.setMessage("Please Wait..!");
            dialog.setIndeterminate(false);
            dialog.setCancelable(true);
            dialog.show();
        }

        protected String doInBackground(String... params) {

            new Thread(new Runnable() {
                public void run() {
                    login();
                }
            }).start();

            return null;
        }

        protected void onPostExecute(String file_url) {
            // dismiss the dialog once got all details
            dialog.dismiss();
        }

    }

    void login() {
        try {

            httpclient = new DefaultHttpClient();
            httppost = new HttpPost(adminLoginURL);

            // add your data
            nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("username", adminUN
                    .getText().toString().trim()));
            nameValuePairs.add(new BasicNameValuePair("password", adminPass
                    .getText().toString().trim()));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            // Execute HTTP Post Request
            response = httpclient.execute(httppost);

            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            final String response = httpclient.execute(httppost,
                    responseHandler);

            boolean matches = response.startsWith("User Found");
            if (matches) {
                // Do something start an Activity or do anything you wanted
                }
            } else {
                showAlert();
            }

        } catch (Exception e) {
            dialog.dismiss();
            System.out.println("Exception : " + e.getMessage());
        }
    }

    public void showAlert() {
        AdminLogin.this.runOnUiThread(new Runnable() {
            public void run() {
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        AdminLogin.this);
                builder.setTitle("Login Error.");
                builder.setMessage("User not Found.")
                        .setCancelable(false)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                            int id) {
                                    }
                                });
                AlertDialog alert = builder.create();
                alert.show();
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_exit, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
        case R.id.action_exit:
            finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }   
}

Create an .xml file to get the username, password, and login button 创建.xml文件以获取用户名,密码和登录按钮

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/ic_wall"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/adminUName"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dip"
        android:hint="Username"
        android:singleLine="true" />

    <requestFocus />

    <EditText
        android:id="@+id/adminPass"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:ems="10"
        android:hint="Password"
        android:inputType="textPassword"
        android:singleLine="true" />

    <Button
        android:id="@+id/adminLogin"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dip"
        android:text="Login"
        android:textColor="#0b84aa" />

</LinearLayout>

You must have PhpMyAdmin to try this in local system, if you have hosted server part then try use the following php code and run it. 您必须让PhpMyAdmin在本地系统中尝试此操作,如果您有托管服务器部分,请尝试使用以下PHP代码并运行它。

adminLogin.php 

<?php
$hostname_localhost ="";
$database_localhost ="";
$username_localhost ="";
$password_localhost ="";
# Make sure above fields are filled with your config values (must)
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);

mysql_select_db($database_localhost, $localhost);


if (empty($_POST['username'])) { 
        echo "Please Enter a name"; 
    } else {
        $username = $_POST['username']; 
    }
    if (empty($_POST['password'])) {
     echo "Please Enter Your Password ";
    } else {
        $password = SHA1($_POST['password']);
    }



$query_search = "select * from adminregister where username = '".$username."' AND password = '".$password."'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
 if($rows == 0) {
 echo "\nNo Such User Found";
 }
 else  {

    echo "User Found";
}
mysql_close();
?>

Note: You need to create database and table specified in mysql to feed and retrieve the data 注意:您需要创建mysql中指定的数据库和表来提供和检索数据

If any errors please leave a comment. 如有任何错误,请发表评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM