HttpURLConnection的常用方法
// 获取链接网络的路径
URL url = new URL(strUrl);
// 准备开启网络.设置访问网络的配置
HttpURLConnection httpURLConnection = (HttpURLConnection) url .openConnection(); httpURLConnection.setConnectTimeout(1000); httpURLConnection.setReadTimeout(1000);
httpURLConnection.connect();
// 获取响应值 int lin = httpURLConnection.getResponseCode();
// 判断返回值是否为200
if (lin == 200) {
// 如果满足条件开始读取信息
// 准备
InputStream inputStream = httpURLConnection.getInputStream();
byte[] bt = new byte[1024];
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// 开始读取内容
int leng = -1;
while ((leng = inputStream.read(bt)) != -1) {
byteArrayOutputStream.write(bt, 0, leng);
}
// 关闭流 inputStream.close();
// 转换成string字符串 String string = byteArrayOutputStream.toString();
HttpGet的联网方式
//得到httplient对象 HttpClient httpClient = new DefaultHttpClient();
//使用get方式访问网络并指定路径 HttpGet httpGet = new HttpGet(url);
//执行联网操作,发送get请求 HttpResponse httpResponse = httpClient.execute(httpGet);
//判断是否为状态码(200)
HttpStatus.SC_PK == httpResponse.toStatusLine().getStatusCode();
//在while循环正,将服务器返回的实体转出字符串
EntityUtils.toString(entity, “utf-8”);
POST请求的网络链接方式
//创建httpClient对象
HttpClient client = new DefaultHttpClient();
//创建http post请求对象,并指定路径 HttpPost post = new HttpPost(url);
// 将要提交的数据以name--value的形式传递
BasicNameValuePair pair = new BasicNameValuePair("name", name);
//把要提交的数据以实体的形式设置到post对象中
List parameters = new ArrayList();
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8"); post.setEntity(entity);
//执行联网操作,进行post请求
HttpResponse response = client.execute(post);
//获取状态行 StatusLine line = response.getStatusLine();
//获取状态码(200)
int statusCode = line.getStatusCode();
//获取实体对象,实体指的是服务器返回的数据
HttpEntity entity = response.getEntity();
//将服务器返回的实体转出字符串 EntityUtils.toString(entity, "utf-8");
三种请求方式,注释在代码的上方