从android中的远程服务器发送/接收文本数据

时间:2011-03-09 06:24:29

标签: android text

HI 我创建了一个应用程序,我隐藏编辑文本框和两个按钮,在我点击按钮事件后,文本框将在运行时弹出,它正在工作,但我需要打字文本应传递给服务器,帮助我。欢迎所有想法

5 个答案:

答案 0 :(得分:3)

如果我理解正确,您在文本框中有文本,并且您希望将该数据发送到服务器。您可以查看其中一个教程/片段,了解有关将数据发布到Web服务器的信息:
http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient
Secure HTTP Post in Android

答案 1 :(得分:1)

JSON或XML可用于将数据发送到远程服务器。

答案 2 :(得分:1)

您好此代码会将您的数据发送到以edittext编写的服务器。对于textview,只需按textview的名称更改edittext的名称。这是代码:

package com.example.asynchttppost;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

    private EditText value;
    private Button btn;
    private ProgressBar pb;
        private TextView tv;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        value=(EditText)findViewById(R.id.editText1);
        btn=(Button)findViewById(R.id.button1);
        pb=(ProgressBar)findViewById(R.id.progressBar1);
                tv =(TextView)findViewById(R.id.TextView1);
        pb.setVisibility(View.GONE);
        btn.setOnClickListener(this);
    }


    public void onClick(View v) {
        // TODO Auto-generated method stub
            if(value.getText().toString().length()<1){

                // out of range
                Toast.makeText(this, "please enter something", Toast.LENGTH_LONG).show();
            }else{
                pb.setVisibility(View.VISIBLE);
                new MyAsyncTask().execute(value.getText().toString());      
            }


    } 

    private class MyAsyncTask extends AsyncTask<String, Integer, Double>{

        @Override
        protected Double doInBackground(String... params) {
            // TODO Auto-generated method stub
            postData(params[0]);
            return null;
        }

        protected void onPostExecute(Double result){
            pb.setVisibility(View.GONE);
            Toast.makeText(getApplicationContext(), "Code Sent", Toast.LENGTH_LONG).show();
        }
        protected void onProgressUpdate(Integer... progress){
            pb.setProgress(progress[0]);
        }

        public void postData(String valueIWantToSend) {
            // Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            //HttpPost httppost = new HttpPost("http://10.0.2.2/chotu/index.php");
            HttpPost httppost = new HttpPost("http://192.168.1.13/educlinic/Widget/AndroidApp");
            try {

                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);

            } 
            catch (ClientProtocolException e) 
            {
                // TODO Auto-generated catch block
            } catch (IOException e)
            {
                // TODO Auto-generated catch block
            }
        }

    }
}

答案 3 :(得分:1)

从服务器获取文本

package com.example.sonasys.net;

import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.sonaprintersd.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

public class SingleContactActivity extends Activity {
    private static final String TAG_CONTACTS = "Contacts";
    private static final String TAG_POSTLINE = "PostLine";
    private static final String TAG_Post_Img = "Post_Img";
    private static final String TAG_Post_Img_O = "Post_Img_O";

    private static String url;
    TextView uid, pid;
    JSONArray contacts = null;
    private ProgressDialog pDialog;
    String details;
    // String imagepath = "http://test2.sonasys.net/Content/WallPost/b3.jpg";
    String imagepath = "";
    Bitmap bitmap;
    ImageView image;
    String imagepath2;

    ArrayList<HashMap<String, String>> contactList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_single_contact);

        url = "http://test2.sonasys.net/MobileApp/GetSinglePost?UserId="
                + uid.getText() + "&Post_ID=" + pid.getText();

        contactList = new ArrayList<HashMap<String, String>>();
        new GetContacts().execute();

    }

    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(SingleContactActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            // pDialog.setTitle("Post Details");
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    contacts = jsonObj.getJSONArray(TAG_CONTACTS);

                    // looping through All Contacts

                    JSONObject c = contacts.getJSONObject(0);

                    details = c.getString(TAG_POSTLINE);
                    imagepath = c.getString(TAG_Post_Img);
                    imagepath2 = c.getString(TAG_Post_Img_O);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**/
            TextView Details = (TextView) findViewById(R.id.details);
            // Details.setText(details);
            Details.setText(android.text.Html.fromHtml(details));

        }
    }

答案 4 :(得分:0)

添加新班级服务处理程序

public class ServiceHandler {

    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;

    public ServiceHandler() {

    }

    /*
     * Making service call
     * @url - url to make request
     * @method - http request method
     * */
    public String makeServiceCall(String url, int method) {



        return this.makeServiceCall(url, method, null);
    }

    /*
     * Making service call
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     * 

     * */

    public String makeServiceCall(String url, int method,List<NameValuePair> params) {

        try {
            // http client

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            // Checking http request method type
            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                // adding post params
                if (params != null) {               
                    httpPost.setEntity(new UrlEncodedFormEntity(params));

                }

                httpResponse = httpClient.execute(httpPost);

            } else if (method == GET) {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return response;

    }