首页 > 技术文章 > 关于HTTP协议在安卓中的小知识点

lewisky 2015-12-18 10:18 原文

工作原理比较简单:就是客户端向服务器发出一条HTTP 请求,服务器收到请求之后会返回一些数据给客户端,然后客户端再对这些数据进行解析和处理就可以。

HttpURLConnection,在安卓上发送http请求 

URL url = new URL("http://www.baidu.com"); 传入网址

HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 获取实例

设置HTTP 请求所使用的方法:connection.setRequestMethod("GET");  从服务器获取数据 POST从服务器发送数据

设置连接超时、读取超时:connection.setConnectTimeout(8000);         connection.setReadTimeout(8000);

获取到服务器返回的输入流:调用getInputStream()方法 

读取输入流:InputStream in = connection.getInputStream();

HTTP 连接关闭:connection.disconnect();

//ScrollView 控件:允许我们以滚动的形式查看屏幕外的那部分内容

提交数据到服务器:

connection.setRequestMethod("POST");

DataOutputStream out = new DataOutputStream(connection.getOutputStream());

out.writeBytes("username=admin&password=123456");

HttpClient的使用和前者却大相径庭。

HttpClient是一个网络访问接口:无法创建实例,通常创建  HttpClient httpClient = new DefaultHttpClient();

发起GET请求,

HttpGet httpGet = new HttpGet("http://www.baidu.com");
httpClient.execute(httpGet);

 

发起POST请求,

HttpPost httpPost = new HttpPost("http://www.baidu.com");

 

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "admin"));
params.add(new BasicNameValuePair("password", "123456"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");
httpPost.setEntity(entity);

httpClient.execute(httpPost);

if (httpResponse.getStatusLine().getStatusCode() == 200) {// 请求和响应都成功了}

HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity);

String response = EntityUtils.toString(entity, "utf-8"); 解决中文乱码

记得声明网络权限:<uses-permission android:name="android.permission.INTERNET" />

 

推荐阅读