android Http通信(访问web server)

下面将3种实现方式,以下代码有的来源于传智播客,有的自己琢磨的。在这感谢传智播客

本人开发使用的android studio,在最新版本中,android不在支持HttpClient,所以,要使用HttpClient要加载库文件。
1,compile ‘org.apache.httpcomponents:httpclient:4.5.2’
或者
2,android {
compileSdkVersion 23
buildToolsVersion ‘23.0.3’
useLibrary ‘org.apache.http.legacy’ //添加这句话,
3,也可以自己导入jar包,(本地导入);

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

            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;
    }
   /*   
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream())
            );
            StringBuffer sb = new StringBuffer();
            String string;
            while ((string = reader.readLine()) != null) {
                sb.append(string);
            }
    }*/
}
 /**
     * 使用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());
        }



    }
}

你可能感兴趣的:(android)