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;
    }
   /* 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<NameValuePair> parameters = new ArrayList<NameValuePair>();
            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<NameValuePair> list = new ArrayList<NameValuePair>();
                        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<NameValuePair> list  = new  ArrayList<NameValuePair>();
                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());
        }

    }
}
时间: 2025-01-10 09:37:10

android Http通信(访问web server)的相关文章

JAVA ANDROID SOCKET通信检测(SERVER)连接是否断开

Pre 解决思路 代码后记: 客户端app上的部分代码 调用: 服务器上: 客户端判断服务器是否还活着代码: PRE 在利用socket写通讯程序的时候,想检测服务器是否还活着. 从网上找了很多资料,都没有自己合适的,最后自己想了个办法,不过也相当于截取了心跳检测的一部分. 这里检测的是远程server的连接,而不是本地是否连接成功.首先想到socket类的方法isClosed().isConnected().isInputStreamShutdown().isOutputStreamShutd

走进http的世界------用C代码模拟浏览器IE(http client)访问web(http server)的行为

在本文中, 我们来玩一下http.   既然你看到了这篇文章, 那就说明你肯定直接或间接借助了http协议(浏览器的实现需要用到http协议). 很多书本把http介绍得玄乎其玄, 高深莫测, 其实,  http也没什么大不了的. 当我们用浏览器看登录www.baidu.com的时候, 浏览器相当于客户端, 而服务端是百度公司掌控着. 要想大致了解http,  网上资料可谓如山如海.作为一名程序员(注意, 我说的是程序猿), 我始终坚信, 没有代码, 没有实践, 只讲理论, 那就是扯淡, 尽管一

Using OAuth 2.0 for Web Server Applications, verifying a user&#39;s Android in-app subscription

在写本文之前先说些题外话. 前段时间游戏急于在GoolePlay上线,明知道如果不加Auth2.0的校验是不安全的还是暂时略过了这一步,果然没几天就发现后台记录与玩家实际付费不太一致,怀疑有玩家盗刷游戏元宝等,并且真实的走过了GooglePlay的所有支付流程完成道具兑换,时间一长严重性可想而知.经过查阅大量google官方文档后把代码补上,并在这里记录下OAuth 2.0 的使用,Google提供了OAuth2.0的好几种使用用途,每种使用方法都有些不同,具体可以看下这篇博客.在这里只写OAu

PHPHub 所有项目正式开源! (包括 iOS, Android, Web, Server, UI)

说明 趁着 团队寻找新项目 的时间空隙, 我们团队 作为练手, 为 PHPHub 做了 iOS 和 Android 客户端, 并开源, 供大家互相学习参考, 欢迎各种提 issue 和 pr ;-) PHPHub related projects PHPHub-iOS by @Aufree PHPHub-Server by @NauxLiu PHPHub-Android by @Kelvin and @Xiaoxiaoyu PHPHub-UI by @Summer and @Aufree PHP

原生Android也能做Web开发了

原生Android也能做Web开发了 版权声明:转载必须注明本文转自严振杰的博客:http://blog.yanzhenjie.com 大家好,今天跟大家介绍一个让原生Android也可以做Web开发的开源项目--AndServer. 开源地址:https://github.com/yanzhenjie/AndServer AndServer是一个Android端的Web服务器,类似Apache或者Tomcat,但又有不同,它是一个普通的Android Library,Android项目Grad

.NET跨平台之旅:升级至ASP.NET 5 RC1,Linux上访问SQL Server数据库

今天微软正式发布了ASP.NET 5 RC1(详见Announcing ASP.NET 5 Release Candidate 1),.NET跨平台迈出了关键一步. 紧跟这次RC1的发布,我们成功地将运行在Linux上的示例站点(http://about.cnblogs.com)升级到了ASP.NET 5 RC1,并且增加了数据库访问功能——基于Entity Framework 7 RC1访问SQL Server数据库. 示例站点页面左侧的导航是从数据库读取数据动态加载的,数据库服务器用的是阿里

android IPC通信(下)-AIDL

android IPC通信(上)-sharedUserId&&Messenger android IPC通信(中)-ContentProvider&&Socket 这篇我们将会着重介绍AIDL的使用方式和原理,要介绍AIDL先要简单介绍一下Binder,而且Messenger,ContentProvider和AIDL的最底层都是使用的Binder. Binder 直观来说,Binder是Android中的一个类,它实现了IBinder接口.从IPC角度来说,Binder是A

转载的web server实例

asp.net—web server模拟网上购物 2014-05-08     我来说两句   来源:asp.net—web server模拟网上购物   收藏    我要投稿 在学vb的时候学到了api函数,今天学习asp.net中的web server,web server和api函数一样都是为用户提供了一个接口,客户端可以在远程直接调用,不需要知道它具体的算法,难易程度,可以直接使用方法. 一.基础 概念: 1.web服务是应用程序 2.它向外界暴露了一个能够通过web进行调用的api 3

自己动手创建一个Web Server(非Socket实现)

目录 介绍 Web Server在Web架构系统中的作用 Web Server与Web网站程序的交互 HTTPListener与Socket两种方式的差异 附带Demo源码概述 Demo效果截图 总结 介绍 本篇文章主要介绍使用HTTPListener类型自己动手创建一个Web Server,创建的Web Server能够接收来自浏览器端的HTTP请求,并且能够传递给对应的Web站点进行处理,最后将处理结果(Html或者其他格式)返回给浏览器. 博主前面曾经介绍过使用Socket模拟Web Se