zoukankan      html  css  js  c++  java
  • Android HttpClient框架get和post方式提交数据(非原创)

    1.fragment_main.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
        <EditText
            android:id="@+id/et_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入用户名" />
    
        <EditText
            android:id="@+id/et_pass"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="请输入密码" />
    
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="getClick"
            android:text="使用get方式提交" />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="postClick"
            android:text="使用post方式提交" />
    
    </LinearLayout>

     2.MainActivity.java

    package com.example.httpclient;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.StatusLine;
    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 android.app.Activity;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.Toast;
    
    import com.example.utils.Utils;
    
    public class MainActivity extends Activity {
        private EditText et_name;
        private EditText et_pass;
        // 创建消息处理器来对消息进行处理
        Handler handler = new Handler() {
        // 重写方法来
        public void handleMessage(android.os.Message msg) {
            Toast.makeText(MainActivity.this, msg.obj.toString(), 0).show();
        }
        };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main);
        // 不能放在类的开头初始化,否则会出现空指针异常,先加载再初始化,不然找不到R.id.et_name
        et_name = (EditText) findViewById(R.id.et_name);
        // 不能放在类的开头初始化,否则会出现空指针异常,先加载再初始化,不然找不到R.id.et_pass
        et_pass = (EditText) findViewById(R.id.et_pass);
        }
    
        public void getClick(View v) {
        // 由于不能在主线程中访问网络,所以需要开一个子线程来访问网络
        Thread t = new Thread() {
            @Override
            public void run() {
            // 获取输入的用户名
            String name = et_name.getText().toString();
            // 获取输入的密码
            String pass = et_pass.getText().toString();
            String url = "http://192.168.1.15:8080/server/serverServlet?name=" + name + "&pass=" + pass;
            // 1.创建HttpClient对象,HttpClient是一个接口,可以使用向上转型来创建对象
            HttpClient client = new DefaultHttpClient();
            // 2.创建HttpGet对象,构造方法的参数就是网址
            HttpGet httpGet = new HttpGet(url);
            try {
                // 3.使用客户端对象,把get请求的对象发送出去
                HttpResponse response = client.execute(httpGet);
                // 4.拿到响应头中的状态行
                StatusLine line = response.getStatusLine();
                // 5.根据状态行中服务端返回的状态码来进行判断是否响应成功
                if (line.getStatusCode() == 200) {
                // 6.拿到返回的响应头的实体
                HttpEntity entity = response.getEntity();
                // 7.拿到实体的内容,其实就是服务器返回的输入流
                InputStream is = entity.getContent();
                // 8.从指定的流总读取数据
                String text = Utils.getTextFromStream(is);
                // 9.创建消息对象
                Message msg = handler.obtainMessage();
                // 10.使用消息对象携带数据
                msg.obj = text;
                // 11.使用消息机制发送消息给主线程,让主线程来刷新UI
                handler.sendMessage(msg);
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            }
        };
        // 启动线程
        t.start();
        }
    
        // post方式提交
        public void postClick(View v) {
        Thread t = new Thread() {
            @Override
            public void run() {
            try {
                // 获取输入的用户名
                String name = et_name.getText().toString();
                // 获取输入的密码
                String pass = et_pass.getText().toString();
                // 定好网址
                String url = "http://192.168.1.15:8080/server/serverServlet?name=" + name + "&pass=" + pass;
                // 1.创建httpClient对象
                HttpClient client = new DefaultHttpClient();
                // 2.创建HttpPost对象
                HttpPost post = new HttpPost(url);
                // 3.将要提交的数据封装到BasicNameValuePair对象中,封装用户名
                BasicNameValuePair bnvp_name = new BasicNameValuePair("name", name);
                // 3.将要提交的数据封装到BasicNameValuePair对象中,封装密码
                BasicNameValuePair bnvp_pass = new BasicNameValuePair("pass", pass);
                // 4.创建list集合,集合中存放的元素必须是继承了NameValuePair类的对象的引用
                List<NameValuePair> parameters = new ArrayList<NameValuePair>();
                // 5.将封装好要发送到服务端的数据添加到集合中
                parameters.add(bnvp_name);
                parameters.add(bnvp_pass);
                // 6.创建UrlEncodedFormEntity对象,携带要发送到服务器的数据,并执行URL的编码,需要将name和pass编码然后再发送到服务端
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
                // 7.设置实体,这个实体中携带有要发送的数据
                post.setEntity(entity);
                // 8.使用客户端发送post请求
                HttpResponse response = client.execute(post);
                // 9.如果成功接收到服务端返回的状态码
                if (response.getStatusLine().getStatusCode() == 200) {
                // 10.获取服务端发回的实体中包含的输入流
                InputStream is = response.getEntity().getContent();
                // 11.从输入流中读取服务端发回的数据
                String text = Utils.getTextFromStream(is);
                // 12.获取消息
                Message msg = handler.obtainMessage();
                // 13.使用消息来携带数据
                msg.obj = text;
                // 14.使用消息机制,发送消息到主线程,让主线程来刷新ui
                handler.sendMessage(msg);
                }
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }
        };
        t.start();
        }
    }

    3.Utils.java

    package com.example.utils;
    
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    
    public class Utils {
    
        public static String getTextFromStream(InputStream is) {
        byte[] buf = new byte[1024];
        int len = -1;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        String text = "";
        try {
            while ((len = is.read(buf)) != -1) {
            baos.write(buf, 0, len);
            }
            text = new String(baos.toByteArray(),"UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            }
            if (baos != null) {
            try {
                baos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }
        }
        return text;
        }
    }

    4.添加网络权限

    <uses-permission android:name="android.permission.INTERNET" />
  • 相关阅读:
    IMP-00009: 导出文件异常结束
    Unknown collation: 'utf8mb4_unicode_ci'
    从 github 执行 git clone 一个大的项目时提示 error: RPC failed
    PHP 中获取当前时间[Datetime Now]
    wordpress 常用函数 checked(),selected(),disabled()
    github 有名的问题【ERROR: Permission to .git denied to user】
    SSH 基础
    mixed content 混合内容
    nginx gzip 模块配置
    markdown 书写表格
  • 原文地址:https://www.cnblogs.com/biao2015/p/5087827.html
Copyright © 2011-2022 走看看