Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android Http通信(訪問web server)

android Http通信(訪問web server)

編輯:關於Android編程

下面將3種實現方式,以下代碼有的來源於傳智播客,有的自己琢磨的。在這感謝傳智播客
1,HttpURLConnection
2,HttpClient
3 簡單的框架,
主要以代碼形式展示;


HttpURLConnection,(get post方式)

1,Obtain a new HttpURLConnection by calling 
URL.openConnection() and casting the result to
 HttpURLConnection.,

2,Prepare the request. The primary property of a 
request is its URI. Request headers may also include 
metadata such as credentials, preferred content types, 
and session cookies.

3,Optionally upload a request body. Instances must be
 configured with setDoOutput(true) if they include a 
 request body. Transmit data by writing to the stream returned by getOutputStream().

4,Read the response. Response headers typically 
include metadata such as the response body's content 
type and length, modified dates and session cookies. 
The response body may be read from the stream returned 
by getInputStream(). If the response has no body, that
 method returns an empty stream.

5,Disconnect. Once the response body has been read, 
the HttpURLConnection should be closed by calling 
disconnect(). Disconnecting releases the resources 
held by a connection so they may be closed or reused.

For example
to retrieve the webpage at http://www.android.com/:

URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
      InputStream in = new BufferedInputStream(urlConnection.getInputStream());
      readStream(in);
    } finally {
      urlConnection.disconnect();
    }

Secure Communication with HTTPS

Calling URL.openConnection() on a URL with the "https"
 scheme will return an HttpsURLConnection, which
  allows for overriding the default HostnameVerifier and SSLSocketFactory. An application-supplied

SSLSocketFactory created from an SSLContext can
 provide a custom X509TrustManager for verifying
  certificate chains and a custom X509KeyManager for
    supplying client certificates. See HttpsURLConnection for more details.

Response Handling

HttpURLConnection will follow up to five HTTP 

redirects. It will follow redirects from one origin server to another. This implementation doesn't follow
 redirects from HTTPS to HTTP or vice versa.

If the HTTP response indicates that an error occurred,
 getInputStream() will throw an IOException. Use       getErrorStream() to read the error response. The
  headers can be read in the normal way using getHeaderFields(),

Posting Content


To upload data to a web server, configure the connection for output using setDoOutput(true).


For best performance, you should call either setFixedLengthStreamingMode(int) when the body length
 is known in advance, or setChunkedStreamingMode(int)
  when it is not. Otherwise HttpURLConnection will be forced to buffer the complete request body in memory 
  before it is transmitted, wasting (and possibly exhausting) heap and increasing latency.

For example, to perform an uplo  
 HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
      urlConnection.setDoOutput(true);
      urlConnection.setChunkedStreamingMode(0);
     OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
      writeStream(out);

      InputStream in = new BufferedInputStream(urlConnection.getInputStream());
      readStream(in);
    } finally {
      urlConnection.disconnect();
    }

下面是我的一個NetUtils的工具類

 package com.sdingba.su.senddataserver.NetUtils;

import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

/**
 * Created by su on 16-4-27.
 * HttpURLConnection 方式登陸
 */
public class NetUtils1 {
    private static final String TAG = "NetUtils1";

    /**
     * 使用post的方式登陸
     * HttpURLConnection
     *
     * @param userName
     * @param password
     * @return
     */
    public static String loginOfPost(String userName, String password) {
        HttpURLConnection conn = null;
//        HttpsURLConnection conn2 = null;
        try {
            URL url = new URL("http://10.10.39.11:8080/Androiddata/Servletdata");

            conn = (HttpURLConnection) url.openConnection();
            //post的方式接受段
            conn.setRequestMethod("POST");
            //鏈接的超時時間
            conn.setConnectTimeout(10000);
            //讀數據的超時時間
            conn.setReadTimeout(5000);
            //TODO 必須設置此方法。允許輸出,一般情況下不允許輸出
            conn.setDoOutput(true);
//        conn.setRequestProperty("Content-Lenght", "234");

            //post請求數據
            String data = "username=" + userName + "&password=" + password;

            //獲取一個輸出流,用於向服務器寫數據,
            // 默認情況下,系統不允許向服務器輸出內容
            OutputStream out = conn.getOutputStream();
            out.write(data.getBytes());
            out.flush();
            out.close();

            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                InputStream is = conn.getInputStream();
                String state = getStringFormInputStream(is);
                return state;
            } else {
                Log.i(TAG, "訪問失敗" + responseCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return null;
    }


    /**
     * 使用get方式登陸
     * HttpURLConnection
     *
     * @param userName
     * @param password
     * @return 登陸狀態
     */
    public static String loginOfGet(String userName, String password) {
        HttpURLConnection conn = null;

        try {
            //URLEncoder.encode()對起進行編碼
            String data = "username=" + URLEncoder.encode(userName, "utf-8") +
                    "&password=" + URLEncoder.encode(password, "UTF-8");
            URL url = new URL("http://10.10.39.11:8080/Androiddata/Servletdata?" + data);
            conn = (HttpURLConnection) url.openConnection();

            //HttpURLConnection
            conn.setRequestMethod("GET");//get和post必須大寫
            //鏈接的超時時間
            conn.setConnectTimeout(10000);
            //讀數據的超時時間
            conn.setReadTimeout(5000);

            int responseCode = conn.getResponseCode();
            if (responseCode == 200) {
                //獲取數據,得到的數據
                InputStream is = conn.getInputStream();
                String state = getStringFormInputStream(is);
                return state;
            } else {
                Log.i(TAG, "訪問失敗" + responseCode);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return null;
    }

    /**
     * 根據流返回一個字符串信息
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    private static String getStringFormInputStream(InputStream inputStream) throws IOException {
        //緩存流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while ((len = inputStream.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        inputStream.close();
        String html = baos.toString();
//        String html = new String(baos.toByteArray(), "GBK");
        baos.close();

        return html;
    }
   /* private static String getStringFromInputStream(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//緩存流
        //ByteArrayOutputStream baos = new ByteArrayOutputStream();//緩存流

        byte[] buffer = new byte[1024];
        int len = -1;

        while((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        is.close();

        String html = baos.toString();  // 把流中的數據轉換成字符串, 采用的編碼是: utf-8

//      String html = new String(baos.toByteArray(), "GBK");

        baos.close();
        return html;
    }*/
}
 /**
     * 使用HttpURLConnection方式進行get查詢數據,
     * @param v
     */
    public void doGet(View v) {
        final String userName = etUserName.getText().toString();
        final String password = etPassword.getText().toString();


        new Thread() {
            @Override
            public void run() {
                //使用get方式去抓取數據
                final String state = NetUtils1.loginOfGet(userName, password);
                //執行在任務的主線程中,
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //就是在主線程中的操作
                        Toast.makeText(MainActivity.this, "返回:"+state + "", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }.start();
    }


    public void doPost(View view) {
        final String userName = etUserName.getText().toString();
        final String password = etPassword.getText().toString();
        Log.i(TAG,""+userName+password);
        new Thread() {
            @Override
            public void run() {
                final String state = NetUtils1.loginOfPost(userName, password);
                //在主線成中顯示。
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "返回:" + state, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }.start();
    }

2,HttpClient (含 get post 方法)

package com.sdingba.su.senddataserver.NetUtils;

import android.support.annotation.Nullable;
import android.util.Log;

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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by su on 16-4-27.
 * HttpClient
 */
public class NetUtils2 {
    private static final String TAG = "NetUtils222";

    /**
     * 使用post方法登陸
     *   * HttpClient *
     * @param userName
     * @param password
     * @return
     */
    public static String loginOfPost(String userName, String password) {
        HttpClient client = null;

        try {
            client = new DefaultHttpClient();
            HttpPost post = new HttpPost("http://10.10.39.11:8080/Androiddata/Servletdata");

            List parameters = new ArrayList();
            NameValuePair pair1 = new BasicNameValuePair("username", userName);
            NameValuePair pair2 = new BasicNameValuePair("password", password);
            parameters.add(pair1);
            parameters.add(pair2);
            //吧post請求參數包裝了一層
            //不寫編碼名稱服務器收數據時亂碼,需要制定字符集為utf8
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
            //設置參數
            post.setEntity(entity);
            //設置請求頭消息
//            post.addHeader("Content-Length", "20");
            //使客服端執行 post 方法
            HttpResponse response = client.execute(post);

            //使用響應對象,獲取狀態嗎,處理內容
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                //使用相應對象獲取實體,。獲得輸入流
                InputStream is = response.getEntity().getContent();
                String text = getStringFromInputStream(is);
                return text;
            }else{
                Log.i(TAG, "請求失敗" + statusCode);
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (client != null) {
                client.getConnectionManager().shutdown();
            }
        }


        return null;
    }

    /**
     * 使用get方式登陸
     * httpClient
     * @param userName
     * @param password
     * @return
     */
    public static String loginOfGet(String userName, String password) {

        HttpClient client = null;

        try {
            //定義一個客戶端
            client = new DefaultHttpClient();

            //定義一個get請求
            String data = "username=" + userName + "&password=" + password;
            HttpGet get = new HttpGet("http://10.10.39.11:8080/Androiddata/Servletdata?" + data);

            //response 服務器相應對象,其中包括了狀態信息和服務返回的數據
            HttpResponse response = client.execute(get);

            //獲取響應嗎
            int statesCode = response.getStatusLine().getStatusCode();
            if (statesCode == 200) {
                InputStream is = response.getEntity().getContent();
                String text = getStringFromInputStream(is);
                return text;
            }else{
                Log.i(TAG, "請求失敗" + statesCode);
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (client != null) {
                client.getConnectionManager().shutdown();
            }
        }

        return null;

    }

    /**
     * 根據流返回一個字符串信息
     * @param is
     * @return
     * @throws IOException
     */
    private static String getStringFromInputStream(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//緩存流
        byte[] buffer = new byte[1024];
        int len = -1;

        while((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        is.close();

        String html = baos.toString();  // 把流中的數據轉換成字符串, 采用的編碼是: utf-8

//      String html = new String(baos.toByteArray(), "GBK");

        baos.close();
        return html;
    }
}

    /**
     * * 使用httpClient方式提交get請求
     */
    public void doHttpClientOfGet(View view) {
        Log.i(TAG,"doHttpClientOfGet");
        final String userName = etUserName.getText().toString();
        final String password = etPassword.getText().toString();
        new Thread() {
            @Override
            public void run() {
                //請求網絡
                final String state = NetUtils2.loginOfGet(userName, password);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, state, Toast.LENGTH_LONG).show();
                    }
                });
            }
        }.start();
    }

    public void doHttpClientOfPost(View v) {
        Log.i(TAG, "doHttpClientOfPost");
        final String userName = etUserName.getText().toString();
        final String password = etPassword.getText().toString();
        new Thread(){
            @Override
            public void run() {
                final String state = NetUtils2.loginOfPost(userName, password);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, "返回:" + state, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }.start();
    }

3,簡單框架, loopj.android.http (含 get post 方法)。。


    /**
     * 使用HttpURLConnection方式進行get查詢數據,
     * @param v
     */
    public void doGet(View v) {
        final String userName = etUserName.getText().toString();
        final String password = etPassword.getText().toString();

        AsyncHttpClient client = new AsyncHttpClient();
        try {
            String data = "username=" + URLEncoder.encode(userName,"UTF-8") +
                    "&password=" + URLEncoder.encode(password);

            client.get("http://10.10.39.11:8080/Androiddata/Servletdata?"
                    + data, new MyResponseHandler());

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


    }


    public void doPost(View view) {
        final String userName = etUserName.getText().toString();
        final String password = etPassword.getText().toString();
        Log.i(TAG,""+userName+password);
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("username", userName);
        params.put("password", password);
        client.post("http://10.10.39.11:8080/Androiddata/Servletdata",
                params, new MyResponseHandler());

    }

    class MyResponseHandler extends AsyncHttpResponseHandler {

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            Toast.makeText(MainActivity2.this,
                    "成功: statusCode: " + statusCode + ", body: " + new String(responseBody),
                    Toast.LENGTH_LONG).show();

        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            Toast.makeText(MainActivity2.this, "失敗: statusCode: " + statusCode, Toast.LENGTH_LONG).show();
        }
    }

下面根據上面的代碼修改 供參考。

public class MainActivity extends AppCompatActivity {
    public static final String TAG = "MainActivity";
    private EditText userName = null;
    private EditText password = null;
    private Button register = null;
    private Button instruction = null;
    private Button login = null;
    private TextView login_title = null;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {//當服務器返回給客戶端標記為1是
                Intent intent = new Intent(MainActivity.this, MainActivity2.class);
                Log.i(TAG, "succes");
                startActivity(intent);
                finish();
            } else {
                Toast.makeText(MainActivity.this, "登陸失敗", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        initListener();
    }

    private void initListener() {
        login.setOnClickListener(new View.OnClickListener() {
            String MyUserName = userName.getText().toString();
            String passwd = password.getText().toString();

            @Override
            public void onClick(View v) {
                new Thread(){
                    @Override
                    public void run() {
                        HttpClient client = new DefaultHttpClient();
                        List list = new ArrayList();
                        NameValuePair pair = new BasicNameValuePair("index", "0");
                        list.add(pair);
                        NameValuePair pair1 = new BasicNameValuePair("username", userName.getText().toString());
                        NameValuePair pair2 = new BasicNameValuePair("password",  password.getText().toString());
                        list.add(pair1);
                        list.add(pair2);
                        try {
                            UrlEncodedFormEntity entiy =
                                    new UrlEncodedFormEntity(list, "UTF-8");

                            HttpPost post = new HttpPost("http://10.10.39.11:8080/AndroidServer/Servlet");
                            post.setEntity(entiy);
                            HttpResponse response = client.execute(post);
                            if (response.getStatusLine().getStatusCode() == 200) {
                                InputStream in = response.getEntity().getContent();
                                handler.sendEmptyMessage(in.read());
                                System.out.println(in.read());
                                in.close();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }finally {
                            if (client != null) {
                                client.getConnectionManager().shutdown();
                            }
                        }


                    }
                }.start();

            }
        });

        this.register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, Agreement.class);
                Log.i(TAG,"secces");
                startActivity(intent);
                finish();
            }
        });

        this.instruction.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, Instruction.class);
                startActivity(intent);
            }
        });
    }

    private void init() {
        userName = (EditText) this.findViewById(R.id.userName);
        password = (EditText) this.findViewById(R.id.password);
        register = (Button) this.findViewById(R.id.register);
        instruction = (Button) this.findViewById(R.id.instruction);
        login = (Button) this.findViewById(R.id.login);
        login_title = (TextView) this.findViewById(R.id.login_title);
    }

public class Register extends Activity {
    public final static int TELEPHONE = 0;
    public final static int EMAIL = 1;
    public final static int QQ = 2;
    public final static int WECHAT = 3;
    public final static int OTHERS = 4;
    private static final String TAG = "Register";

    private EditText userName = null;
    private EditText password = null;
    private EditText rePassword = null;
    private RadioGroup sex = null;
    private RadioButton male = null;
    private RadioButton female = null;
    private Spinner communication = null;
    private Button register = null;
    private Button goback = null;
    private User user = null;
    private boolean usernameCursor = true;// 判讀用戶名輸入框是失去光標還是獲得光標
    private boolean repasswordCursor = true;// 判讀重復密碼輸入框是失去光標還是獲得光標
    private String mySex = null;
    private String myCommunication = null;
    private TextView communication_way_choice = null;
    private EditText communication_content = null;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                Toast.makeText(Register.this, "注冊成功", Toast.LENGTH_SHORT)
                        .show();
                Intent register = new Intent(Register.this, MainActivity.class);
                startActivity(register);
                finish();
            } else {
                Toast.makeText(Register.this, "注冊失敗", Toast.LENGTH_SHORT)
                        .show();
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        init();
        initListener();
    }

    private boolean isUsernameExisted(String username) {
        boolean flag = false;
        return flag;
    }

    private void initListener() {
        /**
         * 當輸入完用戶後,輸入框失去貫標,該用戶的數據在數據庫中是否存在
         */
        this.userName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                String myUserName = userName.getText().toString();
                if (!usernameCursor) {
                    if (isUsernameExisted(myUserName)) {
                        Toast.makeText(Register.this, "該用戶名已經存在,請更改用戶名",
                                Toast.LENGTH_SHORT).show();
                    }
                }

            }
        });
        this.rePassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (repasswordCursor = !repasswordCursor) {
                    if (!checkPassword(password.getText().toString(),rePassword
                            .getText().toString())) {
                        rePassword.setText("");
                        Toast.makeText(Register.this, "兩次密碼不一樣,請重新輸入",
                                Toast.LENGTH_SHORT).show();

                    }
                }
            }
        });
        this.sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == male.getId()) {
                    mySex = "男";
                }else{
                    mySex = "女";
                }
            }
        });
        this.communication.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView parent, View view, int position, long id) {
                myCommunication = parent.getItemAtPosition(position).toString();
                communication_way_choice.setText(myCommunication);
            }

            @Override
            public void onNothingSelected(AdapterView parent) {

            }
        });
        this.register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "register...");
                if (mySex == null || communication_content.getText().toString() == null) {
                    String title = "提示: ";
                    String message = "你的信息不完全,填寫完整信息有助於我們提高更好的服務";
                    new AlertDialog.Builder(Register.this).setTitle(title)
                            .setMessage(message)
                            .setPositiveButton("繼續注冊", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    if (checkPassword(password.getText().toString(), rePassword
                                            .getText().toString())) {
                                        Log.i(TAG,"注冊控件");
                                        excuteRegister();
                                    }else{
                                        rePassword.setText("");
                                        //rePassword.requestFocus();
                                        Toast.makeText(Register.this, "兩次密碼不一樣,111請重新輸入",
                                                Toast.LENGTH_SHORT).show();
                                    }
                                }


                            })
                            .setNegativeButton("返回修改", null).show();


                }else if (checkPassword(password.getText().toString(), rePassword
                        .getText().toString())) {
                    excuteRegister(); Log.i(TAG,"注冊控件222");
                }else{
                    rePassword.setText("");
                    Toast.makeText(Register.this, "兩次密碼不一樣,請重新輸入222",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

        this.goback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Register.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }

    private void excuteRegister() {
        new Thread(){
            @Override
            public void run() {
                super.run();
                HttpClient client = new DefaultHttpClient();
                List list  = new  ArrayList();
                NameValuePair pair = new BasicNameValuePair("index", "2");
                list.add(pair);
                NameValuePair pair1 = new BasicNameValuePair("username", userName.getText().toString());
                NameValuePair pair2 = new BasicNameValuePair("password", password.getText().toString());
                NameValuePair pair3 = new BasicNameValuePair("sex", mySex);
                NameValuePair pair4 = new BasicNameValuePair("communication_way", myCommunication);
                NameValuePair pair5 = new BasicNameValuePair("communication_num", communication_content.getText().toString());

                list.add(pair1);
                list.add(pair2);
                list.add(pair3);
                list.add(pair4);
                list.add(pair5);

                try {
                    HttpEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
                    Log.i(TAG, "HttpPost前");
                    HttpPost post = new HttpPost("http://10.10.39.11:8080/AndroidServer/Servlet");
                    Log.i(TAG, "HTTPPost後");
                    post.setEntity(entity);
                    HttpResponse responce = client.execute(post);
                    Log.i(TAG,"HttpHost前222");
                    if (responce.getStatusLine().getStatusCode() == 200) {
                        InputStream in = responce.getEntity().getContent();
                        handler.sendEmptyMessage(in.read());
                        in.close();
                        Log.i(TAG,"HttpHostg後222");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    private boolean checkPassword(String psw1, String psw2) {
        if (psw1.equals(psw2))
            return true;
        else
            return false;
    }

    private void init() {
        this.userName = (EditText) this.findViewById(R.id.regi_userName);
        this.password = (EditText) this.findViewById(R.id.regi_password);
        this.rePassword = (EditText) this.findViewById(R.id.regi_repassword);
        this.sex = (RadioGroup) this.findViewById(R.id.regi_sex);
        this.male = (RadioButton) this.findViewById(R.id.regi_male);
        this.female = (RadioButton) this.findViewById(R.id.regi_female);
        this.communication = (Spinner) this
                .findViewById(R.id.regi_communication_way);
        this.register = (Button) this.findViewById(R.id.regi_register);
        this.goback = (Button) this.findViewById(R.id.regi_goback);
        this.communication_way_choice = (TextView) findViewById(R.id.communication_way_choice);
        this.communication_content = (EditText) findViewById(R.id.communication_content);
    }
}

下面提高以下最簡單的後台,最簡單,沒有之一(java web)
向深入的,就像寫java web一樣,寫就好,關於http通信,還有很多很好用的框架,

@WebServlet(name = "Servletdata",urlPatterns = "/Servletdata")
public class Servletdata extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("post");
        doGet(request,response);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("dodododo");
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        System.out.println(username+"    "+password);
        if ("sdingba".equals(username) && "123".equals(password)) {
            response.getOutputStream().write("success".getBytes());
        } else {
            response.getOutputStream().write("error".getBytes());
        }



    }
}
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved