12.5.1 生成HTTP请求

    下面对如何生成HTTP请求进行简短的介绍。

    首先通过实例化DefaultHttpClient对象来创建一个HttpClient。

1         HttpClient httpclient=new DefaultHttpClient();

    随后将创建一个HttpPost对象,其表示一个POST请求,指向将要传入的特定的URL。

1         HttpPost httppost=new HttpPost("http://webserver/file-upload-app");

    接下来实例化MultipartEntity。正如刚才所描述的那样,可以包括该类型实体的多个部分。

1         MultipartEntity multipartEntity=new MultipartEntity();

    需要的主要部分是将要上传的实际文件。为此将使用addPart方法,同时传入作为名称的字符串和作为值的FileBody对象。这个FileBody对象接受一个表示要上传的实际文件的File对象作为参数——在当前的情况下,这是在SD卡根目录上的视频文件。

1         multipartEntity.addPart("file", new FileBody(new File(Environment.getExternalStorageDirectory()+"/test.mp3")));

    如果需要添加其他的元素,如用户名、密码等,那么将使用相同的addPart方法,并传入名称和值。在当前情况下,只应该是一个StringBody对象,其中包含字符串类型的实际值。

1             multipartEntity.addPart("username", new StringBody("myusername"));
2             multipartEntity.addPart("password", new StringBody("mypassword"));
3             multipartEntity.addPart("title", new StringBody("A title"));

    一旦设置完MultipartEntity,就通过调用setEntity方法将它传递给HttpPost对象。

1             httppost.setEntity(multipartEntity);

    现在可以执行请求并获得响应。

1             HttpResponse httpresponse=httpclient.execute(httppost);
2             HttpEntity responseentity=httpresponse.getEntity();

    通过调用给定HttpEntity上的getContent方法,可以获得一个InputStream以读取响应。

1             InputStream inputstream=responseentity.getContent();

    为了读取InputStream,可以将它包装在InputStreamReader和BufferedReader中,同时采用通常的读取过程。

1             BufferedReader bufferedreader=new BufferedReader(new InputStreamReader(inputstream));

    我们将使用StringBuilder来保存读取的所有的数据。

1             StringBuilder stringbuilder=new StringBuilder();

    然后逐行读取BufferedReader,直到它返回null。

1             String currentline=null;
2             while((currentline=bufferedreader.readLine())!=null){
3                 stringbuilder.append(currentline+"\n");
4             }

    当读取完成之后,将该StringBuilder对象转换成一个正常的字符串,并将它输出到日志中。

1             String result=stringbuilder.toString();

    最后关闭该InputStream。

1             inputstream.close();

    当然,必须在应用程序中具备访问Internet的权限。因此,需要在AndroidManifest.xml文件中添加以下uses-permission行。

1     <uses-permission android:name="android.permission.INTERNET"/>

    一旦下载和导入了必须的库,实现文件上传将和使用HttpClient类执行正常的HTTP请求一样简单。

 

posted on 2014-09-12 11:31  宁静致远,一览众山小  阅读(262)  评论(0编辑  收藏  举报

导航