第一种:HttpUrlConnection
1将访问的路径转换成URL。
URL url = new URL(path);
2,通过URL获取连接。
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
3,设置请求方式。 这是是get连接
conn.setRequestMethod(GET);
4,设置连接超时时间。
conn.setConnectTimeout(5000);
5,设置请求头的信息。
conn.setRequestProperty(User-Agent, Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0));
6,获取响应码
int code = conn.getResponseCode();
7,针对不同的响应码,做不同的操作
7.1,请求码200,表明请求成功,获取返回内容的输入流
InputStream is = conn.getInputStream();
7.2,将输入流转换成字符串信息
public class StreamTools {
/**
* 将输入流转换成字符串
*
* @param is
* 从网络获取的输入流
* @return
*/
public static String streamToString(InputStream is) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.close();
is.close();
byte[] byteArray = baos.toByteArray();
return new String(byteArray);
} catch (Exception e) {
Log.e(tag, e.toString());
return null;
}
}
7.3,若返回值400,则是返回网络异常,做出响应的处理。
HttpUrlConnection发送GET请求
/**
以后用的时候只需要把 path ,username ,password等参数修改,
* 通过HttpUrlConnection发送GET请求
*
* @param username 这是是请求的参数
* @param password 这是是请求的参数
* @return
*/
public static String loginByGet(String username, String password) {
String path = http://192.168.0.107:8080/WebTest/LoginServerlet?username= + username + &password= + password;
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod(GET);
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream(); // 字节流转换成字符串
return StreamTools.streamToString(is);
} else {
return 网络访问失败;
}
} catch (Exception e) {
e.printStackTrace();
return 网络访问失败;
}
}
HttpUrlConnection发送POST请求
/**
* 通过HttpUrlConnection发送POST请求
*
* @param username
* @param password
* @return
*/
public static String loginByPost(String username, String password) {
String path = http://192.168.0.107:8080/WebTest/LoginServerlet;
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod(POST);
conn.setRequestProperty(Content-Type, application/x-www-form-urlencoded);
String data = username= + username + &password= + password;
conn.setRequestProperty(Content-Length, data.length() + );
// POST方式,其实就是浏览器把数据写给服务器
conn.setDoOutput(true); // 设置可输出流
OutputStream os = conn.getOutputStream(); // 获取输出流
os.write(data.getBytes()); // 将数据写给服务器
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
return StreamTools.streamToString(is);
} else {
return 网络访问失败;
}
} catch (Exception e) {
e.printStackTrace();
return 网络访问失败;
}
}
第二种:HttpClient
HttpClient发送GET请求
步骤:
1,创建HttpClient对象
2,创建HttpGet对象,指定请求地址(带参数)
3,使用HttpClient的execute(),方法执行HttpGet请求,得到HttpResponse对象
4,调用HttpResponse的getStatusLine().getStatusCode()方法得到响应码
5,调用的HttpResponse的getEntity().getContent()得到输入流,获取服务端写回的数据
/**
* 通过HttpClient发送GET请求
*
* @param username
* @param password
* @return
*/
public static String loginByHttpClientGet(String username, String password) {
String path = http://192.168.0.107:8080/WebTest/LoginServerlet?username=
+ username + &password= + password;
HttpClient client = new DefaultHttpClient(); // 开启网络访问客户端
HttpGet httpGet = new HttpGet(path); // 包装一个GET请求
try {
HttpResponse response = client.execute(httpGet); // 客户端执行请求
int code = response.getStatusLine().getStatusCode(); // 获取响应码
if (code == 200) {
InputStream is = response.getEntity().getContent(); // 获取实体内容
String result = StreamTools.streamToString(is); // 字节流转字符串
return result;
} else {
return 网络访问失败;
}
} catch (Exception e) {
e.printStackTrace();
return 网络访问失败;
}
}
HttpClient发送POST请求
1,创建HttpClient对象
2,创建HttpPost对象,指定请求地址
3,创建List,用来装载参数
4,调用HttpPost对象的setEntity()方法,装入一个UrlEncodedFormEntity对象,携带之前封装好的参数
5,使用HttpClient的execute()方法执行HttpPost请求,得到HttpResponse对象
6, 调用HttpResponse的getStatusLine().getStatusCode()方法得到响应码
7, 调用的HttpResponse的getEntity().getContent()得到输入流,获取服务端写回的数据
/**
* 通过HttpClient发送POST请求
*
* @param username
* @param password
* @return
*/
public static String loginByHttpClientPOST(String username, String password) {
String path = http://192.168.0.107:8080/WebTest/LoginServerlet;
try {
HttpClient client = new DefaultHttpClient(); // 建立一个客户端
HttpPost httpPost = new HttpPost(path); // 包装POST请求
// 设置发送的实体参数
List<namevaluepair> parameters = new ArrayList<namevaluepair>();
parameters.add(new BasicNameValuePair(username, username));
parameters.add(new BasicNameValuePair(password, password));
httpPost.setEntity(new UrlEncodedFormEntity(parameters, UTF-8));
HttpResponse response = client.execute(httpPost); // 执行POST请求
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream is = response.getEntity().getContent();
String result = StreamTools.streamToString(is);
return result;
} else {
return 网络访问失败;
}
} catch (Exception e) {
e.printStackTrace();
return 访问网络失败;
}
}
其他开源联网框架
AsyncHttpClient是一个非常优秀的联网框架,不仅支持所有Http请求的方式,而且还支持文件的上传和下载,要知道用HttpUrlConnection写一个文件上传和下载健全功能是很需要花费一定时间和精力的,因为请求头实在是太多了,稍有不慎就会写错。但是AsyncHttpClient已经封装好了这些“麻烦”,我们只需要下载到AsyncHttpClient的jar包或者源码导入项目中,Http,上传,下载等等,只需要几个简单的api即可搞定。 AsyncHttpClient的GitHub主页:https://github.com/AsyncHttpClient/async-http-client/
AsyncHttpClient发送GET请求
1,将下载好的源码拷贝到src目录下
2,创建一个AsyncHttpClient的对象
3,调用该类的get方法发送GET请求,传入请求资源地址URL,创建AsyncHttpResponseHandler对象
4,重写AsyncHttpResponseHandler下的两个方法,onSuccess和onFailure方法
/**
* 通过AsyncHttpClient发送GET请求
*/
public void loginByAsyncHttpGet() {
String path = http://192.168.0.107:8080/WebTest/LoginServerlet?username=zhangsan&password=123;
AsyncHttpClient client = new AsyncHttpClient();
client.get(path, new AsyncHttpResponseHandler() {
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable arg3) {
// TODO Auto-generated method stub
Log.i(TAG, 请求失败: + new String(arg2));
}
@Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
// TODO Auto-generated method stub
Log.i(TAG, 请求成功: + new String(arg2));
}
});
}
AsyncHttpClient发送POST请求
1,将下载好的源码拷贝到src目录下
2,创建一个AsyncHttpClient的对象
3,创建请求参数,RequestParams对象
4,调用该类的post方法发POST,传入请求资源地址URL,请求参数RequestParams,创建AsyncHttpResponseHandler对象
5,重写AsyncHttpResponseHandler下的两个方法,onSuccess和onFailure方法
/**
* 通过AsyncHttpClient发送POST请求
*/
public void loginByAsyncHttpPost() {
String path = http://192.168.0.107:8080/WebTest/LoginServerlet;
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put(username, zhangsan);
params.put(password, 123);
client.post(path, params, new AsyncHttpResponseHandler() {
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable arg3) {
// TODO Auto-generated method stub
Log.i(TAG, 请求失败: + new String(arg2));
}
@Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
// TODO Auto-generated method stub
Log.i(TAG, 请求成功: + new String(arg2));
}
});
}
AsyncHttpClient上传文件
1,将下载好的源码拷贝到src目录下
2,创建一个AsyncHttpClient的对象
3,创建请求参数,RequestParams对象,请求参数仅仅包含文件对象即可,例如:
params.put(profile_picture, new File(/sdcard/pictures/pic.jpg));
4,调用该类的post方法发POST,传入请求资源地址URL,请求参数RequestParams,创建AsyncHttpResponseHandler对象
5,重写AsyncHttpResponseHandler下的两个方法,onSuccess和onFailure方法
1将访问的路径转换成URL。
URL url = new URL(path);
2,通过URL获取连接。
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
3,设置请求方式。 这是是get连接
conn.setRequestMethod(GET);
4,设置连接超时时间。
conn.setConnectTimeout(5000);
5,设置请求头的信息。
conn.setRequestProperty(User-Agent, Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0));
6,获取响应码
int code = conn.getResponseCode();
7,针对不同的响应码,做不同的操作
7.1,请求码200,表明请求成功,获取返回内容的输入流
InputStream is = conn.getInputStream();
7.2,将输入流转换成字符串信息
public class StreamTools {
/**
* 将输入流转换成字符串
*
* @param is
* 从网络获取的输入流
* @return
*/
public static String streamToString(InputStream is) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.close();
is.close();
byte[] byteArray = baos.toByteArray();
return new String(byteArray);
} catch (Exception e) {
Log.e(tag, e.toString());
return null;
}
}
7.3,若返回值400,则是返回网络异常,做出响应的处理。
HttpUrlConnection发送GET请求
/**
以后用的时候只需要把 path ,username ,password等参数修改,
* 通过HttpUrlConnection发送GET请求
*
* @param username 这是是请求的参数
* @param password 这是是请求的参数
* @return
*/
public static String loginByGet(String username, String password) {
String path = http://192.168.0.107:8080/WebTest/LoginServerlet?username= + username + &password= + password;
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod(GET);
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream(); // 字节流转换成字符串
return StreamTools.streamToString(is);
} else {
return 网络访问失败;
}
} catch (Exception e) {
e.printStackTrace();
return 网络访问失败;
}
}
HttpUrlConnection发送POST请求
/**
* 通过HttpUrlConnection发送POST请求
*
* @param username
* @param password
* @return
*/
public static String loginByPost(String username, String password) {
String path = http://192.168.0.107:8080/WebTest/LoginServerlet;
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod(POST);
conn.setRequestProperty(Content-Type, application/x-www-form-urlencoded);
String data = username= + username + &password= + password;
conn.setRequestProperty(Content-Length, data.length() + );
// POST方式,其实就是浏览器把数据写给服务器
conn.setDoOutput(true); // 设置可输出流
OutputStream os = conn.getOutputStream(); // 获取输出流
os.write(data.getBytes()); // 将数据写给服务器
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
return StreamTools.streamToString(is);
} else {
return 网络访问失败;
}
} catch (Exception e) {
e.printStackTrace();
return 网络访问失败;
}
}
第二种:HttpClient
HttpClient发送GET请求
步骤:
1,创建HttpClient对象
2,创建HttpGet对象,指定请求地址(带参数)
3,使用HttpClient的execute(),方法执行HttpGet请求,得到HttpResponse对象
4,调用HttpResponse的getStatusLine().getStatusCode()方法得到响应码
5,调用的HttpResponse的getEntity().getContent()得到输入流,获取服务端写回的数据
/**
* 通过HttpClient发送GET请求
*
* @param username
* @param password
* @return
*/
public static String loginByHttpClientGet(String username, String password) {
String path = http://192.168.0.107:8080/WebTest/LoginServerlet?username=
+ username + &password= + password;
HttpClient client = new DefaultHttpClient(); // 开启网络访问客户端
HttpGet httpGet = new HttpGet(path); // 包装一个GET请求
try {
HttpResponse response = client.execute(httpGet); // 客户端执行请求
int code = response.getStatusLine().getStatusCode(); // 获取响应码
if (code == 200) {
InputStream is = response.getEntity().getContent(); // 获取实体内容
String result = StreamTools.streamToString(is); // 字节流转字符串
return result;
} else {
return 网络访问失败;
}
} catch (Exception e) {
e.printStackTrace();
return 网络访问失败;
}
}
HttpClient发送POST请求
1,创建HttpClient对象
2,创建HttpPost对象,指定请求地址
3,创建List,用来装载参数
4,调用HttpPost对象的setEntity()方法,装入一个UrlEncodedFormEntity对象,携带之前封装好的参数
5,使用HttpClient的execute()方法执行HttpPost请求,得到HttpResponse对象
6, 调用HttpResponse的getStatusLine().getStatusCode()方法得到响应码
7, 调用的HttpResponse的getEntity().getContent()得到输入流,获取服务端写回的数据
/**
* 通过HttpClient发送POST请求
*
* @param username
* @param password
* @return
*/
public static String loginByHttpClientPOST(String username, String password) {
String path = http://192.168.0.107:8080/WebTest/LoginServerlet;
try {
HttpClient client = new DefaultHttpClient(); // 建立一个客户端
HttpPost httpPost = new HttpPost(path); // 包装POST请求
// 设置发送的实体参数
List<namevaluepair> parameters = new ArrayList<namevaluepair>();
parameters.add(new BasicNameValuePair(username, username));
parameters.add(new BasicNameValuePair(password, password));
httpPost.setEntity(new UrlEncodedFormEntity(parameters, UTF-8));
HttpResponse response = client.execute(httpPost); // 执行POST请求
int code = response.getStatusLine().getStatusCode();
if (code == 200) {
InputStream is = response.getEntity().getContent();
String result = StreamTools.streamToString(is);
return result;
} else {
return 网络访问失败;
}
} catch (Exception e) {
e.printStackTrace();
return 访问网络失败;
}
}
其他开源联网框架
AsyncHttpClient是一个非常优秀的联网框架,不仅支持所有Http请求的方式,而且还支持文件的上传和下载,要知道用HttpUrlConnection写一个文件上传和下载健全功能是很需要花费一定时间和精力的,因为请求头实在是太多了,稍有不慎就会写错。但是AsyncHttpClient已经封装好了这些“麻烦”,我们只需要下载到AsyncHttpClient的jar包或者源码导入项目中,Http,上传,下载等等,只需要几个简单的api即可搞定。 AsyncHttpClient的GitHub主页:https://github.com/AsyncHttpClient/async-http-client/
AsyncHttpClient发送GET请求
1,将下载好的源码拷贝到src目录下
2,创建一个AsyncHttpClient的对象
3,调用该类的get方法发送GET请求,传入请求资源地址URL,创建AsyncHttpResponseHandler对象
4,重写AsyncHttpResponseHandler下的两个方法,onSuccess和onFailure方法
/**
* 通过AsyncHttpClient发送GET请求
*/
public void loginByAsyncHttpGet() {
String path = http://192.168.0.107:8080/WebTest/LoginServerlet?username=zhangsan&password=123;
AsyncHttpClient client = new AsyncHttpClient();
client.get(path, new AsyncHttpResponseHandler() {
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable arg3) {
// TODO Auto-generated method stub
Log.i(TAG, 请求失败: + new String(arg2));
}
@Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
// TODO Auto-generated method stub
Log.i(TAG, 请求成功: + new String(arg2));
}
});
}
AsyncHttpClient发送POST请求
1,将下载好的源码拷贝到src目录下
2,创建一个AsyncHttpClient的对象
3,创建请求参数,RequestParams对象
4,调用该类的post方法发POST,传入请求资源地址URL,请求参数RequestParams,创建AsyncHttpResponseHandler对象
5,重写AsyncHttpResponseHandler下的两个方法,onSuccess和onFailure方法
/**
* 通过AsyncHttpClient发送POST请求
*/
public void loginByAsyncHttpPost() {
String path = http://192.168.0.107:8080/WebTest/LoginServerlet;
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put(username, zhangsan);
params.put(password, 123);
client.post(path, params, new AsyncHttpResponseHandler() {
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable arg3) {
// TODO Auto-generated method stub
Log.i(TAG, 请求失败: + new String(arg2));
}
@Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
// TODO Auto-generated method stub
Log.i(TAG, 请求成功: + new String(arg2));
}
});
}
AsyncHttpClient上传文件
1,将下载好的源码拷贝到src目录下
2,创建一个AsyncHttpClient的对象
3,创建请求参数,RequestParams对象,请求参数仅仅包含文件对象即可,例如:
params.put(profile_picture, new File(/sdcard/pictures/pic.jpg));
4,调用该类的post方法发POST,传入请求资源地址URL,请求参数RequestParams,创建AsyncHttpResponseHandler对象
5,重写AsyncHttpResponseHandler下的两个方法,onSuccess和onFailure方法