(三)HttpURLConnection

来源:互联网 发布:c语言数据类型怎么用 编辑:程序博客网 时间:2024/06/12 22:37

Http协议是网络传输中相当重要的一种协议,具体内容在后面会单独写一篇博客,详细总结。

这里先简单介绍一下URL,全称:Uniform Resource Locators  统一资源定位符。Web上的每个资源都有唯一的地址,采用的是URL格式




接下来步入正题:

    Http通信发送请求的方式最常见的有两种,get和post。get把参数放在URL字符后面,例如:

    http://10.0.2.2:8080/AndroidNet/LoginServlet?username=jingzhi&password=123

    post方法参数是放在http的请求中。需要对Http的请求和响应报文比较了解

   所以,我们首先明确使用的请求方式


一.GET请求方式

我们要先构建起一条思路,再去看如何写代码

我们应该需要一个HttpURLConnection的实例,通过它去设置请求方式,以及一些自由的定制参数:设置连接超时、读取超时的ms数,以及服务器希望得到的一些消息头等。之后就可以获取服务器返回的输入流,从这个输入流里面读取数据了。具体代码如下:

还要注意访问网络这种耗时操作必须要在单独的线程中进行,不可以在主线程中完成,否则报错误



具体代码如下:

(1)布局文件:

    <Button        android:id="@+id/btnGetReq"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="loginGetReqMethod"        android:text="Get请求" />    <ScrollView        android:layout_width="match_parent"        android:layout_height="match_parent">        <TextView            android:id="@+id/response"            android:layout_width="match_parent"            android:layout_height="wrap_content" />    </ScrollView>
(2)程序:

    public void loginGetReqMethod(View view) {        new Thread(new Runnable() {            @Override            public void run() {                String path = "http://www.baidu.com";                HttpURLConnection connection = null;                try {                    URL url = new URL(path);                    connection = (HttpURLConnection)url.openConnection();                    connection.setRequestMethod("GET");                    connection.setConnectTimeout(8000);                    connection.setReadTimeout(8000);                    InputStream in = connection.getInputStream();                    //下面对获取到的输入流进行读取                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));                    StringBuilder response = new StringBuilder();                    String line;                    while ((line = reader.readLine()) != null) {                        response.append(line);                    }                    Message msg = handler.obtainMessage(SHOW_BAIDU, response.toString());                    handler.sendMessage(msg);                } catch (IOException e) {                    e.printStackTrace();                } finally {                    if (connection != null) {                        connection.disconnect();                    }                }            }        }).start();    }

二.POST请求:

post请求方式与get请求方式不同的一点是参数传输的方式不同,post请求的参数是在请求报文里面

        new Thread(new Runnable() {            @Override            public void run() {                String path = "http://10.0.2.2:8080/AndroidNet/LoginServlet";                try {                    URL url = new URL(path);                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();  //打开http连接                    conn.setRequestMethod("POST");  // Post 请求不能使用缓存                    conn.setDoOutput(true); // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;                    conn.setDoInput(true);  // 设置是否从httpUrlConnection读入,默认情况下是true;                    conn.setConnectTimeout(1000 * 30);                    conn.setReadTimeout(1000 * 30);                    conn.setUseCaches(false);  // Post 请求不能使用缓存                    conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");  //服务端可以通过request.getParameterMap()获取到参数了,但是在向服务器发送大量的文本、包含非ASCII字符的文本或二进制数据时这种编码方式效率很低//                    conn.setRequestProperty("Content-type","application/x-java-serialized-object ");   // 设定传送的内容类型是可序列化的java对象//                    conn.setRequestProperty("Content-type","multipart/form-data; boundary="+"00content0boundary00\r\n");   // 一种对媒体MIME的格式,一般用来传输大文本或二进制文件上载                    //对服务器端读取或写入数据(使用输入输出流)                    DataOutputStream dos = new DataOutputStream(conn.getOutputStream());  //获取连接的输出流                    dos.writeBytes("username=" + URLEncoder.encode(userNameStr, "GBK"));                    dos.writeBytes("&password=" + URLEncoder.encode(passwordStr,"GBK"));                    dos.flush();                    dos.close();                    //从服务器获取响应数据                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));                    StringBuilder builder = new StringBuilder();                    String line;                    while((line = br.readLine()) != null) {                        builder.append(line);                    }                    String result = builder.toString();                    System.out.println("result=" + result);                    br.close();                    conn.disconnect();                    Message msg = handler.obtainMessage(LOGIN_SUCCESS, result);                    handler.sendMessage(msg);                } catch (MalformedURLException e) {                    e.printStackTrace();                } catch (IOException e) {                    System.out.println(e.toString());                    handler.sendEmptyMessage(LOGIN_ERROR);                }            }        }).start();

这里也把handler处理UI和JSON解析的代码也贴出来,供参考

    private static class MyHandler extends Handler {        private final WeakReference<HttpURLConnectionActivity> weakReference;        public MyHandler(HttpURLConnectionActivity activity) {            weakReference = new WeakReference<HttpURLConnectionActivity>(activity);        }        @Override        public void handleMessage(Message msg) {            HttpURLConnectionActivity activity = weakReference.get();            if (activity != null) {                switch (msg.what) {                    case LOGIN_SUCCESS:                        String json = (String) msg.obj;                        activity.jsonToObject(json);                        break;                    case LOGIN_ERROR:                        activity.info.setText("登录失败,请检查用户名和密码是否正确!");                        break;                    case SHOW_BAIDU:                        activity.response.setText((String)msg.obj);                        break;                }            }        }    }    //解析JSON为对象    public void jsonToObject(String json) {        Gson gson = new Gson();        JsonObject object = gson.fromJson(json, JsonObject.class);        info.setText(object.toString());    }




    



0 0
原创粉丝点击