Android 中HttpURLConnection 的使用

首先要搭建与Android 交互的简单的网络服务端


HttpURLConnection分为两个部分,分为两个部分,请求和回复,回复的时候根据回复的内容来读取。
通过URL.openConnection来得到HttpURLConnection的对象。请求部分分为GET请求和POST 请求,POST请求更安全.都是需要设置请求时间等。
POST 请求还需要设置请求的数据,例如HashMap 来设置键值对,然后通过遍历得到具体的要提交的数据。值的部分 需要通过URLEncode来编码,
POST 请求还需要设置请求的属性,有两个属性必须要设置,Content-Type和Content-Length
POST 请求还需要通过OutputStream 来将数据提交给服务器端。

收到信息回复的时候,如果返回码为200说明正确了,这个时候我们要根据需求来决定使用哪一种输出流,如果需要保存在本地那么就使用FileOutputStream,
如果是仅仅是一次性的信息,可以使用ByteArrayOutputStream来在内存读取,然后释放就好了。



0:HttpURLConnection GET 请求,HttpURLConnection POST 请求

0.1GET 请求:
   URL url = new URL("http://192.168.1.106:8080/tomcat.png");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setConnectTimeout(5000);
            httpURLConnection.setDoInput(true);


0.2 POST 请求:
            url = new URL("http://192.168.1.106:8080/ServerDemo/servlet/LoginServlert");
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setConnectTimeout(5000);
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);//设置可以向服务器传递数据

上面的都几乎一样,最关键的就是这里设置属性的部分,需要设置两个属性,一个是内容类型,一个是内容的长度。然后输出。
通过这里的输出,其实我们也可以是图片或者文件,这样就实现了文件的上传的功能。
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//设置提交的内容的类
            byte[] data = sb.toString().getBytes("utf-8");//注意这里的编码utf-8
            urlConnection.setRequestProperty("Content-Length", String.valueOf(data.length));//设置提交的内容的长度
            //提交数据
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(data);
            outputStream.close();

请求的数据,方法一:
            StringBuilder sb = new StringBuilder("username=哈哈&password=psw");
请求的数据,方法二:
            HashMap params = new HashMap();
            params.put("username", "哈哈");
            params.put("password", "psw");
            StringBuilder sb = new StringBuilder();//把要提交的 数据类型定义为 username=哈哈&password=psw的格式
            for(Map.Entry en:params.entrySet()){//通过Map的遍历的到
                    sb.append(en.getKey())
                            .append("=")
                            .append(URLEncoder.encode(en.getValue(), "utf-8"))//这里的编码别忘记了。
                            .append("&");
            }
            sb.deleteCharAt(sb.length()-1);//删除最后一个&,注意 这里是 length-1,因为是从0开始计数的。


1:接收回复信息

返回信息的读取:读取的时候因为有的数据对于我们是没有必要存储的,有的是需要存储的。需要存储的我们使用FileOutputStream 将它写入到文件中,不需要存储的我们通过ByteArrayOutputStream 在内存中读取然后释放就好了。


1.1 需要存储的我们使用FileOutputStream 将它写入到文件中
            InputStream in = null;
            FileOutputStream fos = null;
            if (httpURLConnection.getResponseCode() == 200) {
                in = httpURLConnection.getInputStream();
                fos = new FileOutputStream(getCacheDir().getPath()+"a.bmp");
                byte[] arr = new byte[1024];
                int len = 0;
                //每次读取 1024个字节,如果读取返回为-1说明到了文件的末尾,结束读取
                while ((len = in.read(arr)) != -1) {
                    fos.write(arr, 0, len);
                }
                //一定要记住要关闭读取流。
                in.close();
                fos.close();
            }


1.2 不需要存储的我们通过ByteArrayOutputStream 在内存中读取然后释放就好了。
            InputStream in = null;
            if(urlConnection.getResponseCode()==200){
                in = urlConnection.getInputStream();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] arr = new byte[1024];
                int len=0;
                while((len=in.read(arr))!=-1){
                    bos.write(arr,0,len);
                }


                byte[] b = bos.toByteArray();
                String ss = new String(b,"utf-8");
                Log.d("kodulf",ss);
            }
            //关闭流
            in.close();



具体的实现代码如下:


0:GET 请求

别忘了权限


例如我的电脑的ip地址是192.168.1.106,那么通过HttpURLConnection 的GET方法下载一个图片的案例如下

package tech.androidstudio.readfileshttpurlconnection;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class MainActivity extends AppCompatActivity implements Runnable {

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

        Thread thread = new Thread(this);
        thread.start();
    }

    @Override
    public void run() {
        try {
            //配置 HttpURLConnection

            //TODO 这里的ip 地址一定不能使localhost 一定要是电脑的或者是正式ip地址.
            //如果写成了localhost,那么就会报错java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused
            //URL url = new URL("http://localhost:8080/tomcat.png");
            URL url = new URL("http://192.168.1.106:8080/tomcat.png");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setConnectTimeout(5000);
            //Sets the flag indicating whether this URLConnection allows input. It cannot be set after the connection is established.
            httpURLConnection.setDoInput(true);

            //获取返回的文件
            InputStream in = null;
            FileOutputStream fos = null;
            if (httpURLConnection.getResponseCode() == 200) {
                in = httpURLConnection.getInputStream();
                //一定不能直接在FileOutputStream里面写文件名,需要添加路径
                //错误的写法:fos = new FileOutputStream("a.bmp");
                //下面存储到内部存储的私有的cache目录里面,注意了生成的文件名是cachea.bmp
                fos = new FileOutputStream(getCacheDir().getPath()+"a.bmp");
                byte[] arr = new byte[1024];
                int len = 0;
                //每次读取 1024个字节,如果读取返回为-1说明到了文件的末尾,结束读取
                while ((len = in.read(arr)) != -1) {
                    fos.write(arr, 0, len);
                }
                //一定要记住要关闭读取流。
                in.close();
                fos.close();
            }

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



1:POST 请求


package tech.androidstudio.readfileshttpurlconnection;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements Runnable {

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

//        Thread thread = new Thread(this);
//        thread.start();

        URL url = null;
        try {
            //定义存储要提交的数据的Map
            //如果 仅仅是为了测试那么直接使用
            //测试的请求+++++++++++++开始+++++++++++++++
            //StringBuilder sb = new StringBuilder("username=哈哈&password=psw");
            //测试的请求++++++++++++++结束++++++++++++++

            //如果为了模拟真实的请求,那么就使用下面的
            //模拟真实的请求+++++++++++++开始+++++++++++++++
            HashMap params = new HashMap();
            params.put("username", "哈哈");
            params.put("password", "psw");
            //把要提交的 数据类型定义为 username=哈哈&password=psw的格式
            StringBuilder sb = new StringBuilder();
            //通过Map的遍历的到
            for(Map.Entry en:params.entrySet()){
                    sb.append(en.getKey())
                            .append("=")
                            .append(URLEncoder.encode(en.getValue(), "utf-8"))
                            .append("&");
            }
            //删除最后一个&,注意 这里是 length-1,因为是从0开始计数的。
            sb.deleteCharAt(sb.length()-1);
            //模拟真实的请求++++++++++++++结束++++++++++++++

            url = new URL("http://192.168.1.106:8080/ServerDemo/servlet/LoginServlert");
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();

            urlConnection.setRequestMethod("POST");
            urlConnection.setConnectTimeout(5000);
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);//设置可以向服务器传递数据

            //设置提交的内容的类型
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            //设置提交的内容的长度
            byte[] data = sb.toString().getBytes("utf-8");//注意这里的编码utf-8
            urlConnection.setRequestProperty("Content-Length", String.valueOf(data.length));

            //提交数据
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(data);
            outputStream.close();


            //判断服务器端的响应码是不是200
            InputStream in = null;
            if(urlConnection.getResponseCode()==200){
                in = urlConnection.getInputStream();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] arr = new byte[1024];
                int len=0;
                while((len=in.read(arr))!=-1){
                    bos.write(arr,0,len);
                }

                byte[] b = bos.toByteArray();
                String ss = new String(b,"utf-8");
                Log.d("kodulf",ss);
            }
            //关闭流
            in.close();


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


    }

    @Override
    public void run() {
        try {
            //配置 HttpURLConnection

            //TODO 这里的ip 地址一定不能使localhost 一定要是电脑的或者是正式ip地址.
            //如果写成了localhost,那么就会报错java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused
            //URL url = new URL("http://localhost:8080/tomcat.png");
            URL url = new URL("http://192.168.1.106:8080/tomcat.png");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setConnectTimeout(5000);
            //Sets the flag indicating whether this URLConnection allows input. It cannot be set after the connection is established.
            httpURLConnection.setDoInput(true);

            //获取返回的文件
            InputStream in = null;
            FileOutputStream fos = null;
            if (httpURLConnection.getResponseCode() == 200) {
                in = httpURLConnection.getInputStream();
                //一定不能直接在FileOutputStream里面写文件名,需要添加路径
                //错误的写法:fos = new FileOutputStream("a.bmp");
                //下面存储到内部存储的私有的cache目录里面,注意了生成的文件名是cachea.bmp
                fos = new FileOutputStream(getCacheDir().getPath()+"a.bmp");
                byte[] arr = new byte[1024];
                int len = 0;
                //每次读取 1024个字节,如果读取返回为-1说明到了文件的末尾,结束读取
                while ((len = in.read(arr)) != -1) {
                    fos.write(arr, 0, len);
                }
                //一定要记住要关闭读取流。
                in.close();
                fos.close();
            }

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


+++++++++++++++++++++++++++++++++++++++++++++

Post服务端的代码可以参考搭建与Android 交互的简单的网络服务端里面的第10步

或者参考下面的,主要就是doPost


import java.io.IOException;
import java.io.PrintWriter;

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


public class LoginServlert extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public LoginServlert() {
		super();
	}

	/**
	 * Destruction of the servlet. 
*/ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet.
* * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println(" A Servlet"); out.println(" "); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" "); out.println(""); out.flush(); out.close(); } /** * The doPost method of the servlet.
* * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); request.setCharacterEncoding("utf-8");//请求方式是 post //先得到客户端提交的用户名和密码 //因为客户端信息被封装在 request对象中,所以需要从request对象中获取用户名密码 String uname = request.getParameter("username");//?username= &psw= //String uname = fun(name); String psw = request.getParameter("password"); //验证 if(uname!=null&&uname.trim()!=""&&psw!=null&&psw.trim()!="") { if("哈哈".equals(uname) && "123".equals(psw)) { out.println("登陆成功"); } else out.println("登陆失败"); }else{ out.println("参数有问题"); } out.flush(); out.close(); /** response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println(" A Servlet"); out.println(" "); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" "); out.println(""); out.flush(); out.close(); */ } /** * Initialization of the servlet.
* * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }





你可能感兴趣的:(3,网络与数据库技术)