HttpURLConnection的经常使用方法服务器
// 获取连接网络的路径网络
URL url = new URL(strUrl);post
// 准备开启网络.设置访问网络的配置url
HttpURLConnection httpURLConnection = (HttpURLConnection) url .openConnection(); httpURLConnection.setConnectTimeout(1000); httpURLConnection.setReadTimeout(1000);spa
httpURLConnection.connect();code
// 获取响应值 int lin = httpURLConnection.getResponseCode();orm
// 判断返回值是否为200对象
if (lin == 200) {utf-8
// 若是知足条件开始读取信息字符串
// 准备
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");
三种请求方式,注释在代码的上方