一:HttpURLConnection
处理文字数据
URLConnection 获取图片
注:URL可以直接InputStream is = URL.openStream();
XML 的应用
向服务器上传文件
DefaultHttpClient
用户登录验证
- URLsourceUrl;
- StringfileName="";
- try{
- sourceUrl=newURL("网址");
- fileName=sourceUrl.getFile();
- fileName=fileName.substring(fileName.lastIndexOf('/')+1);
- fileName="/sdcard/"+(newDate()).getTime()+fileName;
- /*创建临时文件
- FilemyTempFile=File.createTempFile("temfile","."+"mp3");//文件扩展名
- 记录临时文件名
- currentTempFilePath=myTempFile.getAbsolutePath();
- */
- FileOutputStreamfos=newFileOutputStream(fileName);
- intread=0;
- byte[]buffer=newbyte[512];
- HttpURLConnectionconn=(HttpURLConnection)sourceUrl.openConnection();
- conn.setDoInput(true);
- conn.connect();
- intlength=conn.getContentLength();
- InputStreamis=conn.getInputStream();
- do{
- read=is.read(buffer);
- if(read>0){
- fos.write(buffer,0,read);
- }
- }while(read!=-1);
- }catch(MalformedURLExceptione){
- //TODOAuto-generatedcatchblock
- e.printStackTrace();
- return;
- }catch(IOExceptione){
- //TODOAuto-generatedcatchblock
- e.printStackTrace();
- return;
- }
- if(fileName!=""){
- Filefile=newFile(fileName);
- if(file.exists()){
- //根据filename,操作这个文件
- }
- }
- URLimageUrl=null;
- Bitmapbitmap=null;
- try
- {
- /*newURL对象将网址传入*/
- imageUrl=newURL(uriPic);
- }
- catch(MalformedURLExceptione)
- {
- e.printStackTrace();
- }
- try
- {
- /*取得连接*/
- HttpURLConnectionconn=(HttpURLConnection)imageUrl
- .openConnection();
- conn.connect();
- /*取得返回的InputStream*/
- InputStreamis=conn.getInputStream();
- mTextView1.setText(conn.getResponseCode()+"="+conn.getResponseMessage());
- /*将InputStream变成Bitmap*/
- bitmap=BitmapFactory.decodeStream(is);
- /*关闭InputStream*/
- is.close();
- }
- catch(IOExceptione)
- {
- e.printStackTrace();
- }
处理文字数据
- /*将InputStream转成Reader*/
- BufferedReaderin=newBufferedReader(newInputStreamReader(
- conn.getInputStream()));
- StringinputLine;
- /*图文件路径*/
- StringuriPic="";
- /*一行一行读取*/
- while((inputLine=in.readLine())!=null)
- {
- uriPic+=inputLine;
- }
URLConnection 获取图片
- URLaryURI=newURL(myImageURL[position]);
- URLConnectionconn=aryURI.openConnection();
- conn.connect();
- InputStreamis=conn.getInputStream();
- Bitmapbm=BitmapFactory.decodeStream(is);
- is.close();
- imageView.setImageBitmap(bm);
注:URL可以直接InputStream is = URL.openStream();
XML 的应用
- URLurl=newURL(ConstData.queryString+cityParamString);
- SAXParserFactoryspf=SAXParserFactory.newInstance();
- SAXParsersp=spf.newSAXParser();
- XMLReaderxr=sp.getXMLReader();
- myHandlergwh=newmyHandler();
- xr.setContentHandler(gwh);
- InputStreamReaderisr=newInputStreamReader(url.openStream(),"GBK");
- InputSourceis=newInputSource(isr);
- xr.parse(is);
向服务器上传文件
- privatevoiduploadFile()
- {
- Stringend="\r\n";
- StringtwoHyphens="--";
- Stringboundary="*****";
- try
- {
- URLurl=newURL(actionUrl);
- HttpURLConnectioncon=(HttpURLConnection)url.openConnection();
- /*允许Input、Output,不使用Cache*/
- con.setDoInput(true);
- con.setDoOutput(true);
- con.setUseCaches(false);
- /*设置传送的method=POST*/
- con.setRequestMethod("POST");
- /*setRequestProperty*/
- con.setRequestProperty("Connection","Keep-Alive");
- con.setRequestProperty("Charset","UTF-8");
- con.setRequestProperty("Content-Type",
- "multipart/form-data;boundary="+boundary);
- /*设置DataOutputStream*/
- DataOutputStreamds=
- newDataOutputStream(con.getOutputStream());
- ds.writeBytes(twoHyphens+boundary+end);
- ds.writeBytes("Content-Disposition:form-data;"+
- "name=\"file1\";filename=\""+
- newName+"\""+end);
- ds.writeBytes(end);
- /*取得文件的FileInputStream*/
- FileInputStreamfStream=newFileInputStream(uploadFile);
- /*设置每次写入1024bytes*/
- intbufferSize=1024;
- byte[]buffer=newbyte[bufferSize];
- intlength=-1;
- /*从文件读取数据至缓冲区*/
- while((length=fStream.read(buffer))!=-1)
- {
- /*将资料写入DataOutputStream中*/
- ds.write(buffer,0,length);
- }
- ds.writeBytes(end);
- ds.writeBytes(twoHyphens+boundary+twoHyphens+end);
- /*closestreams*/
- fStream.close();
- ds.flush();
- /*取得Response内容*/
- InputStreamis=con.getInputStream();
- intch;
- StringBufferb=newStringBuffer();
- while((ch=is.read())!=-1)
- {
- b.append((char)ch);
- }
- /*将Response显示于Dialog*/
- showDialog(b.toString().trim());
- /*关闭DataOutputStream*/
- ds.close();
- }
- catch(Exceptione)
- {
- showDialog(""+e);
- }
- }
DefaultHttpClient
用户登录验证
- /*账号:david*/
- /*密码:1234*/
- StringuriAPI="http://www.dubblogs.cc:8751/Android/Test/API/TestLogin/index.php";
- StringstrRet="";
- try
- {
- DefaultHttpClienthttpclient=newDefaultHttpClient();
- HttpResponseresponse;
- HttpPosthttpost=newHttpPost(uriAPI);
- List<NameValuePair>nvps=newArrayList<NameValuePair>();
- nvps.add(newBasicNameValuePair("uid",strUID));
- nvps.add(newBasicNameValuePair("upw",strUPW));
- httpost.setEntity(newUrlEncodedFormEntity(nvps,HTTP.UTF_8));
- response=httpclient.execute(httpost);
- HttpEntityentity=response.getEntity();
- //entity=response.getEntity();
- Log.d(TAG,"HTTPPOSTgetStatusLine:"+response.getStatusLine());
- /*HTMLPOSTresponseBODY*/
- strRet=EntityUtils.toString(entity);
- Log.i(TAG,strRet);
- strRet=strRet.trim().toLowerCase();
- List<cookie>cookies=httpclient.getCookieStore().getCookies();
- if(entity!=null)
- {
- entity.consumeContent();
- }
- Log.d(TAG,"HTTPPOSTInitializeofcookies.");
- cookies=httpclient.getCookieStore().getCookies();
- if(cookies.isEmpty())
- {
- Log.d(TAG,"HTTPPOSTCookienotfound.");
- Log.i(TAG,entity.toString());
- }
- else
- {
- for(inti=0;i<cookies.size();i++)
- {
- Log.d(TAG,"HTTPPOSTFoundCookie:"+cookies.get(i).toString());
- }
- }
- if(strRet.equals("y"))
- {
- Log.i("TEST","YES");
- returntrue;
- }
- else
- {
- Log.i("TEST","NO");
- returnfalse;
- }
- }
- catch(Exceptione)
- {
- e.printStackTrace();
- returnfalse;
- }