Android中的HTTP通讯

此文,仅做为个人学习Android,记录成长以及方便复习!

前面使用线程和异步加载配合HttpURLConnection实现通讯,最后使用HttpClient实现通讯)

简单的实现

通过Eclipse EE 软件,使用Servlet+TomCat搭建一个Web项目,接收和响应Android项目发送过来的数据

首先通过Eclipse创建一个项目《web》

创建一个JSP页面 index.jsp,简单粗暴的一个表单页面!

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<form action="MyServlet" method="get">
		姓名:<input type="text" name="name"><br>
		年龄:<input type="text" name="age"><br>
		提交:<input type="submit" value="提交">
	</form>
</body>
</html>

创建一个Servlet处理提交过来的数据 Myservlet.java

package com.rui.servlet;

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

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

/**
 * 处理传过来的值
 */
//3.0版本后通过注解,不用在web.xml编写
@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置编码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		//接收的值,存入字符串
		String name = request.getParameter("name");
		String age =  request.getParameter("age");
		//获取打印对象
		PrintWriter pw =  response.getWriter();
		//响应客户端消息(浏览器或者是安卓端)
		pw.println("服务器的姓名:"+name+"服务器的年龄:"+age);
		//控制台输出
		System.out.println("本地姓名:"+name);
		System.out.println("本地年龄:"+age);
	}

}

运行结果


测试没问题,开始编写Android端

新建项目HttpDemo(通过线程和异步加载实现(AsyncTask)实现)

首先编写界面 action_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.rui.http.MainActivity"
    android:layout_margin="10dp">

   <TextView
       android:id="@+id/tv1"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="姓名:"/>

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/tv1"
        android:layout_alignBaseline="@+id/tv1"/>
    <TextView
        android:id="@+id/tv2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv1"
        android:layout_marginTop="20dp"
        android:text="年龄:"/>

    <EditText
        android:id="@+id/age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/tv2"
        android:layout_below="@+id/tv1"/>
    <Button
        android:id="@+id/bt1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/age"
        android:text="发送"/>
</RelativeLayout>

在清单文件AndroidManifest.xml添加网络权限(凡是需要访问网络的都要加)

 <uses-permission android:name="android.permission.INTERNET"></uses-permission>

编写线程类,实现发送和响应服务器数据HttpThread.java,包含了2个方法,一个使用get请求,一个使用post请求!本次调用dopost方法!

package com.rui.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by qqazl001 on 2018/4/16.
 */


//继承线程类
public class HttpThread extends Thread{
    private String url,name,age;
    //通过构造方法,初始化数值
    public HttpThread(String url,String name,String age){
        this.url = url;
        this.name = name;
        this.age =  age;
    }

    //通过Get方法发送和接收服务端发送回来的响应数据
    public void doGet(){
        //Get方法请求数据,需要拼装URL
        url = url + "?name="+name+"&age="+age;
        //初始化InputStreamReader,BufferedReader
        InputStreamReader isr=null;
        BufferedReader br=null;
        try {
            //实例化URl对象
            URL HttpURL = new URL(url);
            //获取链接对象
            HttpURLConnection conn = (HttpURLConnection) HttpURL.openConnection();
            //设置请求方式为GET
            conn.setRequestMethod("GET");
            //设置超时时间
            conn.setReadTimeout(5000);
            //获取输入流
            isr = new InputStreamReader(conn.getInputStream());
            //输入流转为缓冲流
            br =  new BufferedReader(isr);
            String str;
            StringBuffer sb =  new StringBuffer();

            //循环每行读取存入sb
            while((str = br.readLine())!=null){
                sb.append(str);
            }
            //控制台打印服务器响应结果
            System.out.println("服务器响应:"+sb.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            //InputStreamReader和BuffrerdReader不为空的时候关闭
            if(isr!=null){
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //通过Post方法发送和接收服务端发送回来的响应数据
    public void doPost(){
        //初始化InputStreamReader,BufferedReader
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            //实例化URl对象
            URL Httpurl = new URL(url);
            //获取链接对象
            HttpURLConnection conn = (HttpURLConnection) Httpurl.openConnection();
            //设置请求方式为POSt
            conn.setRequestMethod("POST");
            //设置超时时间
            conn.setReadTimeout(5000);
            //获取输出流
            OutputStream out = conn.getOutputStream();
            //定义POST发送参数
            String content = "name="+name+"&age="+age;
            //发送参数转为字节,向服务端发送
            out.write(content.getBytes());
            //获取输入流
            isr = new InputStreamReader(conn.getInputStream());
            //输入流转缓冲流
            br = new BufferedReader(isr);
            StringBuffer sb = new StringBuffer();
            String str;
            //循环每行读取存入sb
            while((str = br.readLine())!=null){
                sb.append(str);
            }
            //控制台打印服务器响应数据
            System.out.println("服务器回应:"+sb.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //InputStreamReader和BuffrerdReader不为空的时候关闭
            if(isr!=null){
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void run() {
//        doGet();
        doPost();
    }
}

最后编写MainActivon.java,实例化输入框和按钮,按钮实现监听方法,实例化HttpThread并传参!

package com.rui.http;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
    private Button bt1;
    private EditText name,age;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bt1 = (Button)findViewById(R.id.bt1);
        name = (EditText)findViewById(R.id.name);
        age = (EditText)findViewById(R.id.age);

        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String Url = "http://192.168.0.109:8080/web/MyServlet";
                new HttpThread(Url,name.getText().toString(),age.getText().toString()).start();
            }
        });
    }
}
左边的Eclipse是服务端接收安卓端发来的数值,右边的Android Studio控制台打印服务端响应的数据


使用异步加载方式实现!MyAsyncTask.java

package com.rui.http_aysnctask;

import android.os.AsyncTask;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by qqazl001 on 2018/4/18.
 */
//异步加载
//参数1:传入URL
//参数2:进度值为空
//参数3:返回值为空
public class MyAsyncTask extends AsyncTask<String,Void,Void>{
    //初始化参数,通过构造方法传参
    private String name;
    private String age;
    public MyAsyncTask(String name,String age){
        this.name = name;
        this.age = age;
    }

    @Override
    protected Void doInBackground(String... strings) {

        //doGet(strings[0]);
        //获取URL连接,调用doPost方法
        doPost(strings[0]);
        return null;
    }

    //通过get方式发送和响应数据
    public void doGet(String url){
        InputStreamReader isr=null;
        BufferedReader br = null;
        //拼装URL
        url = url + "?name="+name+"&age="+age;
        try {
            //实例化URL
            URL HttpUrl = new URL(url);
            //获取连接对象
            HttpURLConnection conn = (HttpURLConnection) HttpUrl.openConnection();
            //设置发送方式为get
            conn.setRequestMethod("GET");
            //设置超时时间
            conn.setReadTimeout(5000);
            //获取输入流
            isr = new InputStreamReader(conn.getInputStream());
            //输入流转缓冲流
            br = new BufferedReader(isr);
            StringBuffer sb = new StringBuffer();
            String str;
            //逐行读取存入sb
            while((str = br.readLine())!=null){
                sb.append(str);
            }
            //控制台打印服务器响应数据
            System.out.println("服务器说:"+sb.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            //InputStreamReader和BufferedReader不为空则关闭
            if(isr!=null){
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //通过POST方式发送和响应
    public void doPost(String url){
        InputStreamReader isr =null;
        BufferedReader br = null;
        try {
            //实例化URL
            URL Httpurl = new URL(url);
            //获取连接对象
            HttpURLConnection conn = (HttpURLConnection)Httpurl.openConnection();
            //设置发送方式为POST
            conn.setRequestMethod("POST");
            //设置超时时间
            conn.setReadTimeout(5000);
            //设置发送的值
            String content = "name="+name+"&age="+age;
            //获取输出流
            OutputStream out = conn.getOutputStream();
            //发送的值转为字节并发送
            out.write(content.getBytes());
            //获取输入流
            isr = new InputStreamReader(conn.getInputStream());
            //输入流转缓冲流
            br =  new BufferedReader(isr);
            StringBuffer sb =  new StringBuffer();
            String res;
            //逐行读取,存入sb
            while((res=br.readLine())!=null){
                sb.append(res);
            }
            //控制台打印服务器响应数据
            System.out.println("服务器说:"+sb.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            //InputStreamReader和BufferedReader不为空则关闭
            if(isr!=null){
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

后编写MainActivon.java,实例化输入框和按钮,按钮实现监听方法,实例化MyAsyncTask并传参!

package com.rui.http_aysnctask;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    private EditText name,age;
    private Button bt1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = (EditText)findViewById(R.id.name);
        age = (EditText)findViewById(R.id.age);
        bt1 = (Button)findViewById(R.id.bt1);

        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url = "http://192.168.0.109:8080/web/MyServlet";
                String names = name.getText().toString();
                String ages = age.getText().toString();
                new MyAsyncTask(names,ages).execute(url);
            }
        });
    }

}

左边的Eclipse是服务端接收安卓端发来的数值,右边的Android Studio控制台打印服务端响应的数据

--------------------------------------华丽分割线----------------------------------------------

使用一个已经过时了的HttpClient实现使用Get和POST通讯,过时不重要,重要是会使用!

由于Goolge已经不要了这个类,所以在新的Android Studio中没有HttpClient类,所以我们得在build.gradle(app)中添加一句话,才能正常使用!

useLibrary 'org.apache.http.legacy'

准备工作可以了,接下编写一个异步加载类(线程也可以)

package com.rui.http_client;

import android.os.AsyncTask;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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 org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by qqazl001 on 2018/4/18.
 */

public class MyAsyncTask extends AsyncTask<String,Void,Void>{
    //初始化参数
    private String name,age;
    public MyAsyncTask(String name,String age){
        this.name = name;
        this.age = age;
    }

    @Override
    protected Void doInBackground(String... strings) {
        //调用get或者post方法传入url
        //HttpClientGet(strings[0]);
        HttpClientPost(strings[0]);
        return null;
    }

    //使用get方法发送和响应
    public void HttpClientGet(String url){
        //拼接URL
        url = url +"?name="+name+"&age="+age;
        //创建HttpGet对象,使用get方式
        HttpGet httpGet = new HttpGet(url);
        //创建HttpClient对象
        HttpClient httpClient = new DefaultHttpClient();
        try {
            //发送请求
            HttpResponse response = httpClient.execute(httpGet);
            //判断类型,是否发送成功
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                //取出服务器返回数值
                String context = EntityUtils.toString(response.getEntity());
                //打印返回数值
                System.out.println("服务器返回数据:"+context);
            }

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

    //使用post方式发送和响应数据
    public void HttpClientPost(String url){
        //创建post对象,使用post请求
        HttpPost httpPost = new HttpPost(url);
        //创建HttpClient对象
        HttpClient httpClient = new DefaultHttpClient();
        //创建集合,存放传送的值
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        try {
            //list存入数值
            list.add(new BasicNameValuePair("name",name));
            list.add(new BasicNameValuePair("age",age));
            //设置发送的数据
            httpPost.setEntity(new UrlEncodedFormEntity(list));
            //发送数据到服务器
            HttpResponse response = httpClient.execute(httpPost);
            //判断类型,是否成功发送
            if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
                //取回服务器返回数值
                String context = EntityUtils.toString(response.getEntity());
                //打印返回数值
                System.out.println("服务器返回的数值:"+context);
            }

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

在MainActivity.java中进行组件的实例化和按钮的监听事件,以及调用异步加载方法传参!

package com.rui.http_client;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    private EditText name,age;
    private Button bt1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name =  findViewById(R.id.name);
        age = findViewById(R.id.age);
        bt1 = findViewById(R.id.bt1);

        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url = "http://192.168.0.109:8080/web/MyServlet";
                new MyAsyncTask(name.getText().toString(),age.getText().toString()).execute(url);
            }
        });
    }
}

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值