`

HttpURLConnection

 
阅读更多
HttpURLConnection
Java代码 
 
URL sourceUrl;  
String fileName ="";  
          
        try {  
            sourceUrl = new URL("网址");  
            fileName = sourceUrl.getFile();  
            fileName = fileName.substring(fileName.lastIndexOf('/') + 1);             
            fileName = "/sdcard/"+(new Date()).getTime()+fileName;  
             /*创建临时文件 
                File myTempFile = File.createTempFile("temfile",                                 "."+"mp3");//文件扩展名 
         记录临时文件名 
        currentTempFilePath = myTempFile.getAbsolutePath(); 
              */ 
            FileOutputStream fos = new FileOutputStream(fileName);  
            int read = 0;  
            byte[] buffer = new byte[512];  
              
            HttpURLConnection conn = (HttpURLConnection) sourceUrl.openConnection();  
            conn.setDoInput(true);  
            conn.connect();  
            int length = conn.getContentLength();  
              
            InputStream is = conn.getInputStream();  
              
            do{  
                 read = is.read(buffer);  
                 if(read > 0){  
                      fos.write(buffer, 0, read);                      
                 }  
            }while(read != -1);  
              
        } catch (MalformedURLException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();              
            return;  
        } catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();          
            return;  
        }  
        if(fileName !=""){  
            File file = new File(fileName);  
            if (file.exists()){                       
                //根据filename,操作这个文件  
            }  
        } 


URL sourceUrl;
String fileName ="";

try {
sourceUrl = new URL("网址");
fileName = sourceUrl.getFile();
fileName = fileName.substring(fileName.lastIndexOf('/') + 1);
fileName = "/sdcard/"+(new Date()).getTime()+fileName;
             /*创建临时文件
                File myTempFile = File.createTempFile("temfile",                                 "."+"mp3");//文件扩展名
         记录临时文件名
        currentTempFilePath = myTempFile.getAbsolutePath();
              */
FileOutputStream fos = new FileOutputStream(fileName);
int read = 0;
byte[] buffer = new byte[512];

HttpURLConnection conn = (HttpURLConnection) sourceUrl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();

InputStream is = conn.getInputStream();

do{
     read = is.read(buffer);
     if(read > 0){
          fos.write(buffer, 0, read);         
     }
}while(read != -1);

} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
if(fileName !=""){
File file = new File(fileName);
    if (file.exists()){    
    //根据filename,操作这个文件
    }
}



Java代码 
URL imageUrl = null;  
   Bitmap bitmap = null;  
   try 
   {  
     /* new URL对象将网址传入 */ 
     imageUrl = new URL(uriPic);  
   }  
   catch (MalformedURLException e)  
   {  
     e.printStackTrace();  
   }  
   try 
   {  
     /* 取得连接 */ 
     HttpURLConnection conn = (HttpURLConnection) imageUrl  
         .openConnection();  
     conn.connect();  
     /* 取得返回的InputStream */ 
     InputStream is = conn.getInputStream();  
     mTextView1.setText(conn.getResponseCode()+"="+conn.getResponseMessage());  
     /* 将InputStream变成Bitmap */ 
     bitmap = BitmapFactory.decodeStream(is);  
     /* 关闭InputStream */ 
     is.close();  
   }  
   catch (IOException e)  
   {  
     e.printStackTrace();  
   } 

URL imageUrl = null;
    Bitmap bitmap = null;
    try
    {
      /* new URL对象将网址传入 */
      imageUrl = new URL(uriPic);
    }
    catch (MalformedURLException e)
    {
      e.printStackTrace();
    }
    try
    {
      /* 取得连接 */
      HttpURLConnection conn = (HttpURLConnection) imageUrl
          .openConnection();
      conn.connect();
      /* 取得返回的InputStream */
      InputStream is = conn.getInputStream();
      mTextView1.setText(conn.getResponseCode()+"="+conn.getResponseMessage());
      /* 将InputStream变成Bitmap */
      bitmap = BitmapFactory.decodeStream(is);
      /* 关闭InputStream */
      is.close();
    }
    catch (IOException e)
    {
      e.printStackTrace();
    }

处理文字数据
Java代码 
/* 将InputStream转成Reader */ 
      BufferedReader in = new BufferedReader(new InputStreamReader(  
          conn.getInputStream()));  
      String inputLine;  
      /* 图文件路径 */ 
      String uriPic = "";  
      /* 一行一行读取 */ 
      while ((inputLine = in.readLine()) != null)  
      {  
        uriPic += inputLine;  
      } 

/* 将InputStream转成Reader */
      BufferedReader in = new BufferedReader(new InputStreamReader(
          conn.getInputStream()));
      String inputLine;
      /* 图文件路径 */
      String uriPic = "";
      /* 一行一行读取 */
      while ((inputLine = in.readLine()) != null)
      {
        uriPic += inputLine;
      }



URLConnection 获取图片
Java代码 
URL aryURI = new URL(myImageURL[position]);  
 
URLConnection conn = aryURI.openConnection();  
conn.connect();  
 
InputStream is = conn.getInputStream();  
 
Bitmap bm = BitmapFactory.decodeStream(is);  
 
is.close();  
 
imageView.setImageBitmap(bm); 


        URL aryURI = new URL(myImageURL[position]);
       
        URLConnection conn = aryURI.openConnection();
        conn.connect();
      
        InputStream is = conn.getInputStream();
      
        Bitmap bm = BitmapFactory.decodeStream(is);
     
        is.close();
   
        imageView.setImageBitmap(bm);

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

XML 的应用
Java代码 
 
URL url = new URL(ConstData.queryString+cityParamString);  
                      
                    SAXParserFactory spf = SAXParserFactory.newInstance();   
                    SAXParser sp = spf.newSAXParser();   
 
                      
                    XMLReader xr = sp.getXMLReader();  
                      
                    myHandler gwh = new myHandler();   
                    xr.setContentHandler(gwh);   
 
                    InputStreamReader isr =new InputStreamReader(url.openStream(),"GBK");  
                    InputSource is=new InputSource(isr);  
                      
                    xr.parse(is); 


URL url = new URL(ConstData.queryString+cityParamString);

SAXParserFactory spf = SAXParserFactory.newInstance();
                    SAXParser sp = spf.newSAXParser();

                   
                    XMLReader xr = sp.getXMLReader();
                   
                    myHandler gwh = new myHandler();
                    xr.setContentHandler(gwh);

                    InputStreamReader isr =new InputStreamReader(url.openStream(),"GBK");
                    InputSource is=new InputSource(isr);
                   
                    xr.parse(is);



向服务器上传文件
Java代码 
 
private void uploadFile()  
  {  
    String end = "\r\n";  
    String twoHyphens = "--";  
    String boundary = "*****";  
    try 
    {  
      URL url =new URL(actionUrl);  
      HttpURLConnection con=(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 */ 
      DataOutputStream ds =   
        new DataOutputStream(con.getOutputStream());  
      ds.writeBytes(twoHyphens + boundary + end);  
      ds.writeBytes("Content-Disposition: form-data; " +  
                    "name=\"file1\";filename=\"" +  
                    newName +"\"" + end);  
      ds.writeBytes(end);     
 
      /* 取得文件的FileInputStream */ 
      FileInputStream fStream = new FileInputStream(uploadFile);  
      /* 设置每次写入1024bytes */ 
      int bufferSize = 1024;  
      byte[] buffer = new byte[bufferSize];  
 
      int length = -1;  
      /* 从文件读取数据至缓冲区 */ 
      while((length = fStream.read(buffer)) != -1)  
      {  
        /* 将资料写入DataOutputStream中 */ 
        ds.write(buffer, 0, length);  
      }  
      ds.writeBytes(end);  
      ds.writeBytes(twoHyphens + boundary + twoHyphens + end);  
 
      /* close streams */ 
      fStream.close();  
      ds.flush();  
 
      /* 取得Response内容 */ 
      InputStream is = con.getInputStream();  
      int ch;  
      StringBuffer b =new StringBuffer();  
      while( ( ch = is.read() ) != -1 )  
      {  
        b.append( (char)ch );  
      }  
      /* 将Response显示于Dialog */ 
      showDialog(b.toString().trim());  
      /* 关闭DataOutputStream */ 
      ds.close();  
    }  
    catch(Exception e)  
    {  
      showDialog(""+e);  
    }  
  } 


private void uploadFile()
  {
    String end = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    try
    {
      URL url =new URL(actionUrl);
      HttpURLConnection con=(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 */
      DataOutputStream ds =
        new DataOutputStream(con.getOutputStream());
      ds.writeBytes(twoHyphens + boundary + end);
      ds.writeBytes("Content-Disposition: form-data; " +
                    "name=\"file1\";filename=\"" +
                    newName +"\"" + end);
      ds.writeBytes(end);  

      /* 取得文件的FileInputStream */
      FileInputStream fStream = new FileInputStream(uploadFile);
      /* 设置每次写入1024bytes */
      int bufferSize = 1024;
      byte[] buffer = new byte[bufferSize];

      int length = -1;
      /* 从文件读取数据至缓冲区 */
      while((length = fStream.read(buffer)) != -1)
      {
        /* 将资料写入DataOutputStream中 */
        ds.write(buffer, 0, length);
      }
      ds.writeBytes(end);
      ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

      /* close streams */
      fStream.close();
      ds.flush();

      /* 取得Response内容 */
      InputStream is = con.getInputStream();
      int ch;
      StringBuffer b =new StringBuffer();
      while( ( ch = is.read() ) != -1 )
      {
        b.append( (char)ch );
      }
      /* 将Response显示于Dialog */
      showDialog(b.toString().trim());
      /* 关闭DataOutputStream */
      ds.close();
    }
    catch(Exception e)
    {
      showDialog(""+e);
    }
  }


DefaultHttpClient
用户登录验证
Java代码 
/* 账号:david */ 
   /* 密码:1234 */ 
   String uriAPI = "http://www.dubblogs.cc:8751/Android/Test/API/TestLogin/index.php";  
   String strRet = "";  
     
   try 
   {  
     DefaultHttpClient httpclient = new DefaultHttpClient();  
     HttpResponse response;  
     HttpPost httpost = new HttpPost(uriAPI);  
     List <NameValuePair> nvps = new ArrayList <NameValuePair>();  
     nvps.add(new BasicNameValuePair("uid", strUID));   
     nvps.add(new BasicNameValuePair("upw", strUPW));   
       
     httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));  
       
     response = httpclient.execute(httpost);  
     HttpEntity entity = response.getEntity();  
     //entity = response.getEntity();  
       
     Log.d(TAG, "HTTP POST getStatusLine: " + response.getStatusLine());  
       
     /* HTML POST response BODY */ 
     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, "HTTP POST Initialize of cookies.");   
     cookies = httpclient.getCookieStore().getCookies();   
     if (cookies.isEmpty())  
     {  
       Log.d(TAG, "HTTP POST Cookie not found.");  
       Log.i(TAG, entity.toString());  
     }  
     else 
     {  
       for (int i = 0; i < cookies.size(); i++)  
       {  
         Log.d(TAG, "HTTP POST Found Cookie: " + cookies.get(i).toString());   
       }   
     }  
       
       
     if(strRet.equals("y"))  
     {  
       Log.i("TEST", "YES");  
       return true;  
     }  
     else 
     {  
       Log.i("TEST", "NO");  
       return false;  
     }  
   }  
   catch(Exception e)  
   {  
     e.printStackTrace();  
     return false;  
   } 


/* 账号:david */
    /* 密码:1234 */
    String uriAPI = "http://www.dubblogs.cc:8751/Android/Test/API/TestLogin/index.php";
    String strRet = "";
   
    try
    {
      DefaultHttpClient httpclient = new DefaultHttpClient();
      HttpResponse response;
      HttpPost httpost = new HttpPost(uriAPI);
      List <NameValuePair> nvps = new ArrayList <NameValuePair>();
      nvps.add(new BasicNameValuePair("uid", strUID));
      nvps.add(new BasicNameValuePair("upw", strUPW));
     
      httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
     
      response = httpclient.execute(httpost);
      HttpEntity entity = response.getEntity();
      //entity = response.getEntity();
     
      Log.d(TAG, "HTTP POST getStatusLine: " + response.getStatusLine());
     
      /* HTML POST response BODY */
      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, "HTTP POST Initialize of cookies.");
      cookies = httpclient.getCookieStore().getCookies();
      if (cookies.isEmpty())
      {
        Log.d(TAG, "HTTP POST Cookie not found.");
        Log.i(TAG, entity.toString());
      }
      else
      {
        for (int i = 0; i < cookies.size(); i++)
        {
          Log.d(TAG, "HTTP POST Found Cookie: " + cookies.get(i).toString());
        }
      }
     
     
      if(strRet.equals("y"))
      {
        Log.i("TEST", "YES");
        return true;
      }
      else
      {
        Log.i("TEST", "NO");
        return false;
      }
    }
    catch(Exception e)
    {
      e.printStackTrace();
      return false;
    }

未完待续
分享到:
评论

相关推荐

    HttpURLConnection文件下载\httpURLConnection文件下载

    在给定的代码片段中,展示了如何使用`HttpURLConnection`进行文件下载。 首先,我们看到代码引入了`java.io`、`java.net`和`java.util`这三个包。`java.io`包含了输入/输出流,用于处理数据的读写;`java.net`包含...

    JAVA通过HttpURLConnection 上传和下载文件的方法

    JAVA通过HttpURLConnection上传和下载文件的方法 JAVA通过HttpURLConnection上传和下载文件的方法是非常有实用价值的,需要的朋友可以参考下。HttpURLConnection是一个Java类,用于从网络中读取数据或向网络中写入...

    本示例使用HttpUrlConnection实现上传文件

    本示例重点讲解如何利用Java内置的HttpURLConnection类来完成这个任务。HttpURLConnection是Java标准库提供的一种轻量级的HTTP客户端接口,适用于简单的HTTP通信场景。 首先,我们来看一下上传文件的基本流程: 1....

    使用HttpUrlConnection实现上传文件 服务器端代码

    在Java编程环境中,当需要与Web服务器交互,例如上传文件时,`HttpURLConnection`是一个常见的选择,因为它提供了灵活且高效的方式。本篇文章将详细讲解如何使用`HttpURLConnection`实现文件上传,同时涉及到服务器...

    通过HttpURLConnection获取SESSIONID

    import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.Map; public class HttpTest { private HttpURLConnection hc = ...

    AsyncTask结合HttpUrlConnection的例子

    本例子是关于如何将`AsyncTask`与`HttpURLConnection`结合,实现一个简单的网络请求。 `AsyncTask`是Android提供的轻量级异步任务框架,它允许开发者在后台线程执行耗时操作,并在主线程更新UI。`AsyncTask`包含三...

    java后台调用HttpURLConnection类模拟浏览器请求实例(可用于接口调用)

    本篇文章将深入讲解如何使用`HttpURLConnection`类来模拟浏览器请求,并通过实例展示其在接口调用中的应用。 首先,`HttpURLConnection`是`java.net.URLConnection`的一个子类,用于处理HTTP协议。在使用`...

    HttpURLConnection servlet 多文件参数 断点上传

    本知识点将深入探讨如何使用`HttpURLConnection`与Servlet协同工作,处理多文件参数以及实现断点上传功能。 首先,`HttpURLConnection`是Java API中的一个核心类,它负责提供HTTP协议的连接功能。相比Apache ...

    使用HttpURLConnection或HttpClient方式传json值到spring中

    本文将详细介绍如何使用`HttpURLConnection`和`HttpClient`这两种方式来实现这一目标。 首先,让我们从`HttpURLConnection`开始。`HttpURLConnection`是Java内置的HTTP客户端,它简单且易于使用,适用于轻量级的...

    Android-使用HttpURLConnection实现断点续传

    HttpURLConnection是Java标准库提供的一种网络连接接口,适用于Android系统,它提供了更高效、更灵活的网络通信方式。本文将详细介绍如何利用HttpURLConnection实现Android应用中的断点续传功能。 首先,理解断点续...

    HttpURLConnection读取本地目录上传远程服务器

    本话题主要关注如何使用`HttpURLConnection`来实现从本地目录读取资源并上传到远程服务器的功能。 首先,`HttpURLConnection`是`java.net.URL`类的子类,它可以建立与指定URL所代表的服务器的连接,并执行HTTP协议...

    Httpurlconnection

    在这个主题中,我们将深入探讨HttpURLConnection的基本操作及其在实际应用中的使用。 首先,了解HttpURLConnection的基本结构是非常重要的。它继承自URLConnection类,提供了对HTTP协议的支持。通过URL对象的open...

    使用HttpURLConnection下载图片

    在本例中,我们将探讨如何使用`HttpURLConnection`来下载图片,这是一个基础但实用的网络编程任务。下面我们将详细介绍这个过程,并涉及到的相关知识点。 1. **HttpURLConnection简介**: `HttpURLConnection`是`...

    java实现多次HttpURLConnection共享session

    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); // 设置请求体,比如username=foo&password=bar // 发送请求,读取响应,获取Set-Cookie头 ``` ...

    android HttpURLConnection上传图片demo

    这个"android HttpURLConnection上传图片demo"提供了一个具体的示例,教我们如何使用HttpURLConnection来完成这一任务。HttpURLConnection是Java标准库中的一个类,它允许Android应用程序与HTTP服务器进行通信,执行...

    Android HttpURLConnection.getResponseCode()错误解决方法

    正文:我在使用HttpURLConnection.getResponseCode()的时候直接报错是IOException错误,responseCode = -1。一直想不明白,同一个程序我调用了两次,结果有一个链接一直OK,另一个却一直报这个错误。后来发现两个...

    HttpURLConnection使用总结示例源码

    本篇文章将深入探讨HttpURLConnection的使用方法、特性以及一些关键的示例代码。 一、HttpURLConnection简介 HttpURLConnection继承自URLConnection,它提供了对HTTP协议的直接支持。相比于HttpClient,...

    Java自带的HttpURLConnection访问接口实现文件上传

    在本文中,我们将深入探讨如何使用HttpURLConnection实现文件上传,同时也会涉及普通参数的传递。 首先,我们需要理解HTTP请求的基本结构。HTTP请求通常由以下几个部分组成:请求行、请求头、空行和请求体。在文件...

    android 联网请求的两种方式HttpURLConnection和HttpClient

    常见的联网请求方式有两种:HttpURLConnection和HttpClient。下面将详细讲解这两种方法,以及它们如何处理POST和GET请求。 **HttpURLConnection** HttpURLConnection是Java标准库提供的类,自Android 2.3(API级别9...

    Android HttpURLConnection 读取网络图片.rar

     HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();// 取得连接  conn.connect();  InputStream is = conn.getInputStream();//取得返回的InputStream  bitmap = BitmapFactory....

Global site tag (gtag.js) - Google Analytics