android系统中提供了3种通信接口:
- 标准Java接口:java.net
- Apache接口:org.apache.http
- android网络接口:android.net.http
网络编程在开发无线应用程序过程中起到了重要的作用。在android系统中包括ApacheHttpClient库,此库位执行android中的网络操作的首选方法。除此之外,android还允许通过标准的java连网api(jva.net包)来访问网络。
在android系统中,存在如下与网络连接相关的包。
- java.net :java.net 提供连网相关的类,包括流和数据套接字、internet协议及通用的http处理,此为多用途的连网资源,经验丰富的java开发人员可立即使用此惯用的包来创建应用程序。
- java.io :经管未明确连网,但java.io仍然非常重要。此包中的各项类通过其他java包中提供的套接字和链接来使用。他们也可以用来与本地文件进行交互(与网络交互时经常发生)
- java.nio :java.niob包含表示具体数据类型的缓冲的各种类,便于基于java语言的两个端口之间的网络通信。
- org.apache.*:org.apache.表示可为进行http通信提供精细控制和功能的各种包。可将apache识别为普通的开源服务器。
- android.net :android.net 包括可信java.net.* 类之外的各种附加的网络接入套接字。包括URL类,他通常在传统连网之外的android应用程序中使用。
- android.net.http:包含可操作SSL证书的各种累类。
- android.net.wifi:包含可管理android平台中wifi所有方面的各种类,并非所有的设备均配备wifi能力。
- android.telephone.gsm:包含管理和发送短信消息所要求的个各种类。
使用Apache接口
- apache 接口基础
在apache httpclient 库中,以下对网络连接有用的各种包。
- org.apache.http.HttpResponse
2.org.apache.http.client.HttpClient
3.org.apache.http.client.methods.HttpGet
4.org.apache.http.client.DefaultHttpClient
5.HttpClient httpclient = new DefaultHttpClient()
如果想从服务器检索词信息,则需要使用HttpGet类的构造器,例如下面的代码。
HttpGet request = new HttpGet("http://innovator.samsungmobile.com")
然后使用HttpClient的execute()方法中的HttpGet对象来检索HttpResponse对象,
HttpResponse response = client.execute(request)
接着读取已检索的响应,
BufferReader rd = new BufferReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while((line = rd.readline()) != null){
Log.d("output:",line);
}
- Apache 应用要点
在android系统中,可以采用HttpPost和HttpGet来 封装post和get请求,再使用HttpClient的execute()方法发送post和get请求并返回服务器的响应数据。
Android中的android.net.* 实际上是通过对Apache的HttpClient的封装来实现的一个HTTP编程接口。在Android6.0版本直接删除了HttpClient类库。下面看一个例子:
//创建HttpClient
private HttpClient createHttpClient() {
HttpParams mDefaultHttpParams = new BasicHttpParams();
//设置连接超时
HttpConnectionParams.setConnectionTimeout(mDefaultHttpParams, 15000);
//设置请求超时
HttpConnectionParams.setSoTimeout(mDefaultHttpParams, 15000);
HttpConnectionParams.setTcpNoDelay(mDefaultHttpParams, true);
HttpProtocolParams.setVersion(mDefaultHttpParams, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(mDefaultHttpParams, HTTP.UTF_8);
//持续握手
HttpProtocolParams.setUseExpectContinue(mDefaultHttpParams, true);
HttpClient mHttpClient = new DefaultHttpClient(mDefaultHttpParams);
return mHttpClient;
}
private void useHttpClientGet(String url) {
HttpGet mHttpGet = new HttpGet(url);
mHttpGet.addHeader("Connection", "Keep-Alive");
try {
HttpClient mHttpClient = createHttpClient();
HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
HttpEntity mHttpEntity = mHttpResponse.getEntity();
int code = mHttpResponse.getStatusLine().getStatusCode();
if (null != mHttpEntity) {
InputStream mInputStream = mHttpEntity.getContent();
String respose = converStreamToString(mInputStream);
Log.i("wangshu", "请求状态码:" + code + "\n请求结果:\n" + respose);
mInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private String converStreamToString(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
String respose = sb.toString();
return respose;
}
HttpURLConnection
post例子:
private void test(){
HttpURLConnection httpURLConnection =null;
try{
URL url = new URL("http://baidu.com");
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setRequestMethod("POST");
// 添加header
httpURLConnection.setRequestProperty("Connection","Keep-Alive");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
StringBuilder mStringBuilder=new StringBuilder();
List<NameValuePair> paramsList = new ArrayList<>();
paramsList.add(new NameValuePair("username", "moon"));
paramsList.add(new NameValuePair("password", "123"));
for (NameValuePair pair:paramsList){
if(!TextUtils.isEmpty(mStringBuilder)){
mStringBuilder.append("&");
}
mStringBuilder.append(URLEncoder.encode(pair.getName(),"UTF-8"));
mStringBuilder.append("=");
mStringBuilder.append(URLEncoder.encode(pair.getParams(),"UTF-8"));
}
BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
writer.write(mStringBuilder.toString());
writer.flush();
writer.close();
httpURLConnection.connect();
InputStream mInputStream = httpURLConnection.getInputStream();
int code = httpURLConnection.getResponseCode();
//将返回信息都出来
String respose = converStreamToString(mInputStream);
mInputStream.close();
}catch (IOException io){
io.printStackTrace();
}
}
class NameValuePair{
String params ;
String name;
public String getParams() {
return params;
}
public void setParams(String params) {
this.params = params;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
NameValuePair(String params, String value){
}
}
网友评论