Android应用经常会和服务器端交互,这就需要手机客户端发送网络请求,下面介绍四种常用网络请求方式,我这边是通过Android单元测试来完成这四种方法的,还不清楚Android的单元测试的同学们请看Android开发技巧总结中的Android单元测试的步骤一文。
java.net包中的HttpURLConnection类
Get方式:
- // Get方式请求
- public static void requestByGet() throws Exception {
- String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";
- // 新建一个URL对象
- URL url = new URL(path);
- // 打开一个HttpURLConnection连接
- HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
- // 设置连接超时时间
- urlConn.setConnectTimeout(5 * 1000);
- // 开始连接
- urlConn.connect();
- // 判断请求是否成功
- if (urlConn.getResponseCode() == HTTP_200) {
- // 获取返回的数据
- byte[] data = readStream(urlConn.getInputStream());
- Log.i(TAG_GET, "Get方式请求成功,返回数据如下:");
- Log.i(TAG_GET, new String(data, "UTF-8"));
- } else {
- Log.i(TAG_GET, "Get方式请求失败");
- }
- // 关闭连接
- urlConn.disconnect();
- }
Post方式:
- // Post方式请求
- public static void requestByPost() throws Throwable {
- String path = "https://reg.163.com/logins.jsp";
- // 请求的参数转换为byte数组
- String params = "id=" + URLEncoder.encode("helloworld", "UTF-8")
- + "&pwd=" + URLEncoder.encode("android", "UTF-8");
- byte[] postData = params.getBytes();
- // 新建一个URL对象
- URL url = new URL(path);
- // 打开一个HttpURLConnection连接
- HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
- // 设置连接超时时间
- urlConn.setConnectTimeout(5 * 1000);
- // Post请求必须设置允许输出
- urlConn.setDoOutput(true);
- // Post请求不能使用缓存
- urlConn.setUseCaches(false);
- // 设置为Post请求
- urlConn.setRequestMethod("POST");
- urlConn.setInstanceFollowRedirects(true);
- // 配置请求Content-Type
- urlConn.setRequestProperty("Content-Type",
- "application/x-www-form-urlencode");
- // 开始连接
- urlConn.connect();
- // 发送请求参数
- DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
- dos.write(postData);
- dos.flush();
- dos.close();
- // 判断请求是否成功
- if (urlConn.getResponseCode() == HTTP_200) {
- // 获取返回的数据
- byte[] data = readStream(urlConn.getInputStream());
- Log.i(TAG_POST, "Post请求方式成功,返回数据如下:");
- Log.i(TAG_POST, new String(data, "UTF-8"));
- } else {
- Log.i(TAG_POST, "Post方式请求失败");
- }
- }
org.apache.http包中的HttpGet和HttpPost类
Get方式:
- // HttpGet方式请求
- public static void requestByHttpGet() throws Exception {
- String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";
- // 新建HttpGet对象
- HttpGet httpGet = new HttpGet(path);
- // 获取HttpClient对象
- HttpClient httpClient = new DefaultHttpClient();
- // 获取HttpResponse实例
- HttpResponse httpResp = httpClient.execute(httpGet);
- // 判断是够请求成功
- if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {
- // 获取返回的数据
- String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
- Log.i(TAG_HTTPGET, "HttpGet方式请求成功,返回数据如下:");
- Log.i(TAG_HTTPGET, result);
- } else {
- Log.i(TAG_HTTPGET, "HttpGet方式请求失败");
- }
- }
Post方式:
- // HttpPost方式请求
- public static void requestByHttpPost() throws Exception {
- String path = "https://reg.163.com/logins.jsp";
- // 新建HttpPost对象
- HttpPost httpPost = new HttpPost(path);
- // Post参数
- List
params = new ArrayList(); - params.add(new BasicNameValuePair("id", "helloworld"));
- params.add(new BasicNameValuePair("pwd", "android"));
- // 设置字符集
- HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
- // 设置参数实体
- httpPost.setEntity(entity);
- // 获取HttpClient对象
- HttpClient httpClient = new DefaultHttpClient();
- // 获取HttpResponse实例
- HttpResponse httpResp = httpClient.execute(httpPost);
- // 判断是够请求成功
- if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {
- // 获取返回的数据
- String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
- Log.i(TAG_HTTPGET, "HttpPost方式请求成功,返回数据如下:");
- Log.i(TAG_HTTPGET, result);
- } else {
- Log.i(TAG_HTTPGET, "HttpPost方式请求失败");
- }
- }
以上是一些部分代码,测试的时候在测试类中运行对应的测试方法即可。
package com.example.shezhi;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class Update
{
String res=" ";
int ites;
String version="1";
/////////////////////////////////////////////////////////////////////////////////////////
public String getupdate(){
//先将参数放入List,再对参数进行URL编码
List params = new LinkedList();
params.add(new BasicNameValuePair("param1", "1"));
params.add(new BasicNameValuePair("param2", "value2"));
//对参数编码
String param = URLEncodedUtils.format(params, "UTF-8");
//baseUrl
String baseUrl = "http://******/index1.jsp";
//将URL与参数拼接
HttpGet getMethod = new HttpGet(baseUrl + "?" + param);
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(getMethod);
res="已经请求";
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //发起GET请求
try {
HttpResponse response = httpClient.execute(getMethod); //发起GET请求
ites=response.getStatusLine().getStatusCode(); //获取响应码
System.out.println(ites+"aaa");
res="1213"+EntityUtils.toString(response.getEntity(), "utf-8");//获取服务器响应内容
System.out.println(res+"vvv");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
/********************************************************************************************
/**
* HttpClient Post方法
* @return
*/
public String Postupdate(){
String urlPath="http://******/index1.jsp";
String realPath=urlPath.replaceAll(" ", "");//把多余的空格替换掉
HttpPost httpRequest=new HttpPost(realPath);
// 添加要传递的参数
List params = new ArrayList();
NameValuePair pair1 = new BasicNameValuePair("username", "gzw");
NameValuePair pair2 = new BasicNameValuePair("password", "123");
params.add(pair1);
params.add(pair2);
try
{
// 设置字符集
HttpEntity httpentity = new UrlEncodedFormEntity(params, "utf-8");
// 请求httpRequest
httpRequest.setEntity(httpentity);
// 取得默认的HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 取得HttpResponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
// HttpStatus.SC_OK表示连接成功
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
// 取得返回的字符串
String strResult = EntityUtils.toString(httpResponse.getEntity());
res=strResult;
}
else
{
res="失败";
}
}catch (Exception e)
{
e.printStackTrace();
}
return res;
}
/********************************************************************************************/
/**
* 调用java类 get方法
*/
public String get_update(){
String urlPath="http://******/index1.jsp"+"?type=save&version="+version+"";
String realPath=urlPath.replaceAll(" ", "");//把多余的空格替换掉
try
{
if(getRequest(realPath))
{
//成功
res="成功";
}
}catch (Exception e)
{
res="失败";
}
return res;
}
/**
* java类 get方法
* @return
*/
//get请求,有文件长度大小限制
public static boolean getRequest(String urlPath) throws Exception
{
URL url=new URL(urlPath);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setReadTimeout(5*1000);
if(con.getResponseCode()==200)
{
return true;
}
return false;
}
/********************************************************************************************
/**
* 调用下面java类 Post方法
* @return
*/
public String post_update(){
String urlPath="http://www.gdhdcy.com/hdleague1/index1.jsp";
Map map=new HashMap();//用集合来做,比字符串拼接来得直观
map.put("type", "save");
map.put("version", version);
try
{
if(postRequest(urlPath,map))
{
//成功
res="成功";
}
}catch (Exception e)
{
res="失败";
}
return res;
}
/**
* java类 post方法
* @return
*/
//post请求,无文件长度大小限制
public static boolean postRequest(String urlPath,Map map) throws Exception
{
StringBuilder builder=new StringBuilder(); //拼接字符
//拿出键值
if(map!=null && !map.isEmpty())
{
for(Map.Entry param:map.entrySet())
{
builder.append(param.getKey()).append('=').append(URLEncoder.encode(param.getValue(), "utf-8")).append('&');
}
builder.deleteCharAt(builder.length()-1);
}
//下面的Content-Length: 是这个URL的二进制数据长度
byte b[]=builder.toString().getBytes();
URL url=new URL(urlPath);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
con.setRequestMethod("POST");
con.setReadTimeout(5*1000);
con.setDoOutput(true);//打开向外输出
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//内容类型
con.setRequestProperty("Content-Length",String.valueOf(b.length));//长度
OutputStream outStream=con.getOutputStream();
outStream.write(b);//写入数据
outStream.flush();//刷新内存
outStream.close();
//状态码是不成功
if(con.getResponseCode()==200)
{
return true;
}
return false;
}
}