http通信
HTTP(HyperText Transfer Protocol)是超文本转移协议的缩写,它用于传送WWW方式的数据,关于HTTP协议的详细内容请参考RFC2616。HTTP协议采用了请求/响应模型。客户端向服务器发送一个请求,请求头包含请求的方法、URL、协议版本、以及包含请求修饰符、客户信息和内容的类似于MIME的消息结构。服务器以一个状态行作为响应,相应的内容包括消息协议的版本,成功或者错误编码加上包含服务器信息、实体元信息以及可能的实体内容。
通常HTTP消息包括客户机向服务器的请求消息和服务器向客户机的响应消息。这两种类型的消息由一个起始行,一个或者多个头域,一个指示头域结束的空行和可选的消息体组成。HTTP的头域包括通用头,请求头,响应头和实体头四个部分。每个头域由一个域名,冒号(:)和域值三部分组成。域名是大小写无关的,域值前可以添加任何数量的空格符,头域可以被扩展为多行,在每行开始处,使用至少一个空格或制表符。
?? 最常用的Http请求无非是get 和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
?? android提供了HttpURLConnection和HttpCliient接口来开发HTTP程序:
使用HttpURLConnection接口
???? 访问无需参数的网页
//http地址String httpUrl = "http://192.168.1.110:8080/http1.jsp";//获得的数据String resultData = "";URL url = null;try{//构造一个URL对象url = new URL(httpUrl); }catch (MalformedURLException e){Log.e(DEBUG_TAG, "MalformedURLException");}if (url != null){try{//使用HttpURLConnection打开连接HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();//得到读取的内容(流)InputStreamReader in = new InputStreamReader(urlConn.getInputStream());// 为输出创建BufferedReaderBufferedReader buffer = new BufferedReader(in);String inputLine = null;//使用循环来读取获得的数据while (((inputLine = buffer.readLine()) != null)){//我们在每一行后面加上一个"\n"来换行resultData += inputLine + "\n";} //关闭InputStreamReaderin.close();//关闭http连接urlConn.disconnect();//设置显示取得的内容if ( resultData != null ){mTextView.setText(resultData);}else {mTextView.setText("读取的内容为NULL");}}catch (IOException e){Log.e(DEBUG_TAG, "IOException");}}
?当访问有参数的jsp网页时,只需要在url的末端加上参数即可,这是因为httpurlconnection默认的访问方式为GET,
url:http://192.168.1.110:8080/http1.jsp?par=values
当要以post方式访问时,需要设置进行setRequestMethod设置,如果无参数直接访问,有参数的话要通过writeBytes写入数据流。
示例:
try{String httpUrl = "http://192.168.1.110:8080/httpget.jsp";// 使用HttpURLConnection打开连接HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();//因为这个是post请求,设立需要设置为trueurlConn.setDoOutput(true);urlConn.setDoInput(true); // 设置以POST方式urlConn.setRequestMethod("POST"); // Post 请求不能使用缓存urlConn.setUseCaches(false);urlConn.setInstanceFollowRedirects(true); // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成, // 要注意的是connection.getOutputStream会隐含的进行connect。urlConn.connect();//DataOutputStream流 DataOutputStream out = new DataOutputStream(urlConn.getOutputStream()); //要上传的参数 String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312"); //将要上传的内容写入流中 out.writeBytes(content); //刷新、关闭 out.flush(); out.close(); //获取数据 BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));String inputLine = null;//使用循环来读取获得的数据while (((inputLine = reader.readLine()) != null)){//我们在每一行后面加上一个"\n"来换行resultData += inputLine + "\n";} reader.close();//关闭http连接urlConn.disconnect();//设置显示取得的内容if ( resultData != null ){mTextView.setText(resultData);}else {mTextView.setText("读取的内容为NULL");}}catch (IOException e){Log.e(DEBUG_TAG, "IOException");}
?如果是下载一幅图片并显示,则将下载的InputStream转化为BitMap即可
InputStream is=conn.getInputStream();Bitmap bt=BitmapFactory.decodeStream(is);return bt;.
?上述是通过标准java接口来实现http,如果需要更加复杂的应用,可以使用android提供的HttpClient
GET方式访问
String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";//HttpGet连接对象HttpGet httpRequest = new HttpGet(httpUrl);try{//取得HttpClient对象HttpClient httpclient = new DefaultHttpClient();//请求HttpClient,取得HttpResponseHttpResponse httpResponse = httpclient.execute(httpRequest);//请求成功if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){//取得返回的字符串String strResult = EntityUtils.toString(httpResponse.getEntity());mTextView.setText(strResult);}else{mTextView.setText("请求错误!");} }catch (ClientProtocolException e){mTextView.setText(e.getMessage().toString());}
?POST方式访问网页
String httpUrl = "http://192.168.1.110:8080/httpget.jsp";//HttpPost连接对象HttpPost httpRequest = new HttpPost(httpUrl);//使用NameValuePair来保存要传递的Post参数List<NameValuePair> params = new ArrayList<NameValuePair>();//添加要传递的参数params.add(new BasicNameValuePair("par", "HttpClient_android_Post"));try{//设置字符集HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");//请求httpRequesthttpRequest.setEntity(httpentity);//取得默认的HttpClientHttpClient httpclient = new DefaultHttpClient();//取得HttpResponseHttpResponse httpResponse = httpclient.execute(httpRequest);//HttpStatus.SC_OK表示连接成功if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){//取得返回的字符串String strResult = EntityUtils.toString(httpResponse.getEntity());mTextView.setText(strResult);}else{mTextView.setText("请求错误!");}}catch (ClientProtocolException e){mTextView.setText(e.getMessage().toString());}
?转自:http://xuyuanshuaaa.iteye.com/blog/981720