【问题标题】:Android, send string from app to web serverAndroid,将字符串从应用程序发送到网络服务器
【发布时间】:2014-10-29 11:20:47
【问题描述】:

我正在尝试制作一个应用程序,我应该将数据从应用程序发送到 Web 服务器。 到目前为止,我一直在搜索并且无法找到一个有效的示例,我发现一些使用 asynctask 的示例不起作用,因此感谢您的帮助!

【问题讨论】:

  • 向我们展示您到目前为止所做的尝试,然后寻求帮助。或者先做一些谷歌搜索,因为你会看到大量与 Android 中的客户端服务器代码相关的链接。

标签: android web-services android-asynctask


【解决方案1】:

试试下面的代码:-

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;

    }   
}

查看以下链接了解更多信息:-

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

【讨论】:

    【解决方案2】:

    试试这个,

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

    创建一个 .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>
    

    您必须有 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();
    ?>
    

    注意:您需要创建在mysql中指定的数据库和表来提供和检索数据

    如有错误请留言。

    【讨论】:

    • 请考虑包含一些关于您的答案的信息,而不是简单地发布代码。我们试图提供的不仅仅是“修复”,而是帮助人们学习。您应该解释原始代码中的问题、您所做的不同之处以及您的更改为何有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 2020-01-28
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多