android网络连接总结

一:HttpURLConnection
Java代码
  1. URLsourceUrl;
  2. StringfileName="";
  3. try{
  4. sourceUrl=newURL("网址");
  5. fileName=sourceUrl.getFile();
  6. fileName=fileName.substring(fileName.lastIndexOf('/')+1);
  7. fileName="/sdcard/"+(newDate()).getTime()+fileName;
  8. /*创建临时文件
  9. FilemyTempFile=File.createTempFile("temfile","."+"mp3");//文件扩展名
  10. 记录临时文件名
  11. currentTempFilePath=myTempFile.getAbsolutePath();
  12. */
  13. FileOutputStreamfos=newFileOutputStream(fileName);
  14. intread=0;
  15. byte[]buffer=newbyte[512];
  16. HttpURLConnectionconn=(HttpURLConnection)sourceUrl.openConnection();
  17. conn.setDoInput(true);
  18. conn.connect();
  19. intlength=conn.getContentLength();
  20. InputStreamis=conn.getInputStream();
  21. do{
  22. read=is.read(buffer);
  23. if(read>0){
  24. fos.write(buffer,0,read);
  25. }
  26. }while(read!=-1);
  27. }catch(MalformedURLExceptione){
  28. //TODOAuto-generatedcatchblock
  29. e.printStackTrace();
  30. return;
  31. }catch(IOExceptione){
  32. //TODOAuto-generatedcatchblock
  33. e.printStackTrace();
  34. return;
  35. }
  36. if(fileName!=""){
  37. Filefile=newFile(fileName);
  38. if(file.exists()){
  39. //根据filename,操作这个文件
  40. }
  41. }

Java代码
  1. URLimageUrl=null;
  2. Bitmapbitmap=null;
  3. try
  4. {
  5. /*newURL对象将网址传入*/
  6. imageUrl=newURL(uriPic);
  7. }
  8. catch(MalformedURLExceptione)
  9. {
  10. e.printStackTrace();
  11. }
  12. try
  13. {
  14. /*取得连接*/
  15. HttpURLConnectionconn=(HttpURLConnection)imageUrl
  16. .openConnection();
  17. conn.connect();
  18. /*取得返回的InputStream*/
  19. InputStreamis=conn.getInputStream();
  20. mTextView1.setText(conn.getResponseCode()+"="+conn.getResponseMessage());
  21. /*将InputStream变成Bitmap*/
  22. bitmap=BitmapFactory.decodeStream(is);
  23. /*关闭InputStream*/
  24. is.close();
  25. }
  26. catch(IOExceptione)
  27. {
  28. e.printStackTrace();
  29. }

处理文字数据
Java代码
  1. /*将InputStream转成Reader*/
  2. BufferedReaderin=newBufferedReader(newInputStreamReader(
  3. conn.getInputStream()));
  4. StringinputLine;
  5. /*图文件路径*/
  6. StringuriPic="";
  7. /*一行一行读取*/
  8. while((inputLine=in.readLine())!=null)
  9. {
  10. uriPic+=inputLine;
  11. }



URLConnection 获取图片
Java代码
  1. URLaryURI=newURL(myImageURL[position]);
  2. URLConnectionconn=aryURI.openConnection();
  3. conn.connect();
  4. InputStreamis=conn.getInputStream();
  5. Bitmapbm=BitmapFactory.decodeStream(is);
  6. is.close();
  7. imageView.setImageBitmap(bm);

注:URL可以直接InputStream is = URL.openStream();

XML 的应用
Java代码
  1. URLurl=newURL(ConstData.queryString+cityParamString);
  2. SAXParserFactoryspf=SAXParserFactory.newInstance();
  3. SAXParsersp=spf.newSAXParser();
  4. XMLReaderxr=sp.getXMLReader();
  5. myHandlergwh=newmyHandler();
  6. xr.setContentHandler(gwh);
  7. InputStreamReaderisr=newInputStreamReader(url.openStream(),"GBK");
  8. InputSourceis=newInputSource(isr);
  9. xr.parse(is);


向服务器上传文件
Java代码
  1. privatevoiduploadFile()
  2. {
  3. Stringend="\r\n";
  4. StringtwoHyphens="--";
  5. Stringboundary="*****";
  6. try
  7. {
  8. URLurl=newURL(actionUrl);
  9. HttpURLConnectioncon=(HttpURLConnection)url.openConnection();
  10. /*允许Input、Output,不使用Cache*/
  11. con.setDoInput(true);
  12. con.setDoOutput(true);
  13. con.setUseCaches(false);
  14. /*设置传送的method=POST*/
  15. con.setRequestMethod("POST");
  16. /*setRequestProperty*/
  17. con.setRequestProperty("Connection","Keep-Alive");
  18. con.setRequestProperty("Charset","UTF-8");
  19. con.setRequestProperty("Content-Type",
  20. "multipart/form-data;boundary="+boundary);
  21. /*设置DataOutputStream*/
  22. DataOutputStreamds=
  23. newDataOutputStream(con.getOutputStream());
  24. ds.writeBytes(twoHyphens+boundary+end);
  25. ds.writeBytes("Content-Disposition:form-data;"+
  26. "name=\"file1\";filename=\""+
  27. newName+"\""+end);
  28. ds.writeBytes(end);
  29. /*取得文件的FileInputStream*/
  30. FileInputStreamfStream=newFileInputStream(uploadFile);
  31. /*设置每次写入1024bytes*/
  32. intbufferSize=1024;
  33. byte[]buffer=newbyte[bufferSize];
  34. intlength=-1;
  35. /*从文件读取数据至缓冲区*/
  36. while((length=fStream.read(buffer))!=-1)
  37. {
  38. /*将资料写入DataOutputStream中*/
  39. ds.write(buffer,0,length);
  40. }
  41. ds.writeBytes(end);
  42. ds.writeBytes(twoHyphens+boundary+twoHyphens+end);
  43. /*closestreams*/
  44. fStream.close();
  45. ds.flush();
  46. /*取得Response内容*/
  47. InputStreamis=con.getInputStream();
  48. intch;
  49. StringBufferb=newStringBuffer();
  50. while((ch=is.read())!=-1)
  51. {
  52. b.append((char)ch);
  53. }
  54. /*将Response显示于Dialog*/
  55. showDialog(b.toString().trim());
  56. /*关闭DataOutputStream*/
  57. ds.close();
  58. }
  59. catch(Exceptione)
  60. {
  61. showDialog(""+e);
  62. }
  63. }

DefaultHttpClient
用户登录验证
Java代码
  1. /*账号:david*/
  2. /*密码:1234*/
  3. StringuriAPI="http://www.dubblogs.cc:8751/Android/Test/API/TestLogin/index.php";
  4. StringstrRet="";
  5. try
  6. {
  7. DefaultHttpClienthttpclient=newDefaultHttpClient();
  8. HttpResponseresponse;
  9. HttpPosthttpost=newHttpPost(uriAPI);
  10. List<NameValuePair>nvps=newArrayList<NameValuePair>();
  11. nvps.add(newBasicNameValuePair("uid",strUID));
  12. nvps.add(newBasicNameValuePair("upw",strUPW));
  13. httpost.setEntity(newUrlEncodedFormEntity(nvps,HTTP.UTF_8));
  14. response=httpclient.execute(httpost);
  15. HttpEntityentity=response.getEntity();
  16. //entity=response.getEntity();
  17. Log.d(TAG,"HTTPPOSTgetStatusLine:"+response.getStatusLine());
  18. /*HTMLPOSTresponseBODY*/
  19. strRet=EntityUtils.toString(entity);
  20. Log.i(TAG,strRet);
  21. strRet=strRet.trim().toLowerCase();
  22. List<cookie>cookies=httpclient.getCookieStore().getCookies();
  23. if(entity!=null)
  24. {
  25. entity.consumeContent();
  26. }
  27. Log.d(TAG,"HTTPPOSTInitializeofcookies.");
  28. cookies=httpclient.getCookieStore().getCookies();
  29. if(cookies.isEmpty())
  30. {
  31. Log.d(TAG,"HTTPPOSTCookienotfound.");
  32. Log.i(TAG,entity.toString());
  33. }
  34. else
  35. {
  36. for(inti=0;i<cookies.size();i++)
  37. {
  38. Log.d(TAG,"HTTPPOSTFoundCookie:"+cookies.get(i).toString());
  39. }
  40. }
  41. if(strRet.equals("y"))
  42. {
  43. Log.i("TEST","YES");
  44. returntrue;
  45. }
  46. else
  47. {
  48. Log.i("TEST","NO");
  49. returnfalse;
  50. }
  51. }
  52. catch(Exceptione)
  53. {
  54. e.printStackTrace();
  55. returnfalse;
  56. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值