[android] HttpURLConnection的初步学习

本文介绍了Android中使用HttpURLConnection进行网络编程的基础知识,包括为何选择HttpURLConnection、使用流程、配置方法,以及POST请求的关键步骤。HttpURLConnection的connect()函数建立TCP连接,HTTP请求在调用getInputStream()时发送。代码示例展示了如何与服务器交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在学习android端的网络编程,前面写了socket有关的总结,这篇总结Http中的HttpURLConnection方法。

Http的网络编程其实有两种:HttpURLConnection和HttpClient。这两个HTTP客户端都支持HTTPS协议、流媒体的上传和下载、配置超时时间、Ipv6协议和连接池等。这两者更提倡用哪一种网上众说纷纭,提供几篇我认为讲的不错的:

网络连接之HttpURLConnection和HttpClient

网络连接之HttpURLConnection和HttpClient

之所以选择先学习HttpURLConnection,主要是这篇文章:HTTP请求用HttpUrlConnection还是HttpClient好

并且在httpclient在android6.0过时(This interface was deprecated(废弃) in API level 22.Please use openConnection() instead. Please visit this webpage for further details.)。Android官方建议开发者根据API版本来决定使用哪一个版本的HTTP客户端。分析网络开源库Volley可以发现当API版本超过9时,使用HttpURLConnection,否则使用HttpClient。

当然对于学习技术的,并没有好坏之分,不能因为这个而放弃另外一种方法,所以后面还会再写HttpClient方法的。

http通信使用最多的是Get和Post。Post和Get的不同之处在于Get的参数放在URL字串中,而Post的参数放在http请求数据中。HttpURLConnection继承自URLConnection,都是抽象类,无法直接实例化对象。其对象主要通过URL的openConnection方法获得。openConnection方法只创建URLConnection或HttpURLConnection实例,但是不进行真正的连接操作,并且每次openConnection都创建一个新的实例。在连接之前,可以设置一些属性,比如超时时间等。HttpURLConnection默认使用Get方法,如果要使用Post方法,则需要使用setRequestMethod方法。


HttpURLConnection的使用流程:

1)创建URL对象:URL realUrl = new URL(requestUrl);
2)通过HttpURLConnection对象,向网络地址发送请求:HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
3)设置容许输出:conn.setDoOutput(true);
4)设置不使用缓存:conn.setUseCaches(false);
5)设置使用POST的方式发送:conn.setRequestMethod("POST"); 默认是用get方法
6)设置维持长连接:conn.setRequestProperty("Connection", "Keep-Alive");
7)设置文件字符集:conn.setRequestProperty("Charset", "UTF-8");
8)设置文件长度:conn.setRequestProperty("Content-Length", String.valueOf(data.length));
9)设置文件类型:conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
10)以流的方式输出.
总结:
--发送POST请求必须设置允许输出
--不要使用缓存,容易出现问题.
--在开始用HttpURLConnection对象的setRequestProperty()设置,就是生成HTML文件头


HttpURLConnection.connect函数,实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。无论是post还是get,http请求实际上直到HttpURLConnection.getInputStream()这个函数里面才正式发送出去。
对connection对象的一切配置(那一堆set函数)都必须要在connect()函数执行之前完成。而对outputStream的写操作,又必须要在inputStream的读操作之前。这些顺序实际上是由http请求的格式决定的。

http请求实际上由两部分组成,一个是http头,所有关于此次http请求的配置都在http头里面定义,一个是正文content,在connect()函数里面,会根据HttpURLConnection对象的配置值生成http头,因此在调用connect函数之前,就必须把所有的配置准备好。

紧接着http头的是http请求的正文,正文的内容通过outputStream写入,实际上outputStream不是一个网络流,充其量是个字符串流,往里面写入的东西不会立即发送到网络,而是在流关闭后,根据输入的内容生成http正文。

至此,http请求的东西已经准备就绪。在getInputStream()函数调用的时候,就会把准备好的http请求正式发送到服务器了,然后返回一个输入流,用于读取服务器对于此次http请求的返回信息。由于http请求在getInputStream的时候已经发送出去了(包括http头和正文),因此在getInputStream()函数之后对connection对象进行设置(对http头的信息进行修改)或者写入outputStream(对正文进行修改)都是没有意义的了,执行这些操作会导致异常的发生。


下面展示代码实例。首先在服务端起一个特别简单的servlet,直接拿了别人的:

ServletDemo.java

package routon;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletDemo extends HttpServlet {

	public ServletDemo() {
		super();
	}


	public void destroy() {
		super.destroy();
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		System.out.println("Android项目Get请求数据:"+URLDecoder.decode(request.getParameter("param"), "utf-8"));
		response.getWriter().print("GET接收成功");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
		System.out.println("Android项目Post请求数据:"+URLDecoder.decode(request.getParameter("param"), "utf-8"));
		response.getWriter().print("POST接收成功");
	}


	public void init() throws ServletException {
		// Put your code here
	}

}

web的配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>ServletDemo</servlet-name>
    <servlet-class>routon.ServletDemo</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>ServletDemo</servlet-name>
    <url-pattern>/ServletDemo</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

代码部分,因为想直接显示效果,强 解除主线程网络访问限制,实际开发中另起一个线程,注释还是挺详细的:

AndroidHttpDemoActivity

package com.example.cxlveu.httptest;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class AndroidHttpDemoActivity extends Activity {

    private EditText et_send = null;
    private TextView tv_show = null;
    private Button postBtn, getBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_android_http_demo);

        StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        et_send = (EditText)findViewById(R.id.senddata);
        tv_show = (TextView)findViewById(R.id.getdata);
        postBtn = (Button)findViewById(R.id.sendsubmit2);
        getBtn = (Button)findViewById(R.id.sendsubmit);

        postBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String strUrl = null;
                URL url = null;

                try {
                    strUrl = "http://192.168.11.50:8080/HttpServlet/ServletDemo";
                    // 封装访问服务器的地址
                    url = new URL(strUrl);
                    Log.i("Post发送数据:", et_send.getText().toString());
                    // 打开服务器
                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                    // 设置输入输出流
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    // 设置超时时间
                    conn.setConnectTimeout(5000);
                    // 设置不使用缓存
                    conn.setUseCaches(false);
                    conn.setInstanceFollowRedirects(true);
                    // 设置使用POST的方式发送:
                    conn.setRequestMethod("POST");
                    // 设置维持长连接:
                    conn.setRequestProperty("Connection", "Keep-Alive");
                    // 设置文件字符集:
                    conn.setRequestProperty("Charset", "UTF-8");
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.connect();
                    // 封装写给服务器的数据(这里是要传递的参数)
                    DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream());

                    String content = "param=" + URLEncoder.encode(URLEncoder.encode(
                            et_send.getText().toString(), "UTF-8"),"UTF-8");
                    outputStream.writeBytes(content);
                    outputStream.flush();
                    outputStream.close();


                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String line = null, result = "";
                    while((line = br.readLine()) != null){
                        result += line;
                    }

                    br.close();
                    conn.disconnect();

                    tv_show.setText(result);

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });

        getBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String strUrl = null;
                URL url = null;

                try {
                    strUrl = "http://192.168.11.50:8080/HttpServlet/ServletDemo?param=" +
                            URLEncoder.encode(URLEncoder.encode(et_send.getText().toString(), "UTF-8"),"UTF-8") ;
                    // 封装成URL
                    url = new URL(strUrl);
                    Log.i("get发送数据:", et_send.getText().toString());
                    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
                //    InputStreamReader in = new InputStreamReader(connection.getInputStream());
                    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                    String line = null, result = "";
                    while((line = br.readLine()) != null){
                        result += line;
                    }

                    br.close();
                    connection.disconnect();

                    tv_show.setText(result);


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

配置xml文件activity_android_http_demo.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:layout_marginLeft="20dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="发送框:"/>

        <EditText
            android:layout_width="240dip"
            android:layout_height="wrap_content"
            android:text="测试数据"
            android:id="@+id/senddata"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="接收框:"/>

        <EditText
            android:layout_width="240dip"
            android:layout_height="wrap_content"
            android:id="@+id/getdata"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal"
        android:layout_marginTop="20dp">
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center_horizontal"
            android:orientation="horizontal" >
            <Button
                android:id="@+id/sendsubmit"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:text="GET发送" />
            <Button
                android:id="@+id/sendsubmit2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:text="POST发送" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值