• 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+"
    ");
    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请求一样简单。

  • 相关阅读:
    lucas定理计算组合数
    西电校赛网络赛J题 lucas定理计算组合数
    bestcoder#37_1001 字符串,贪心
    codeforces#297div2_d bfs,2*2法判断矩阵里的矩形
    codeforces#297div2_c 贪心
    codeforces#297div2_b 贪心,字符串,哈希
    poj2983——差分约束,bellman_ford
    poj1201——差分约束,spfa
    图的邻接表存储
    hiho1093 ——spfa
  • 原文地址:https://www.cnblogs.com/ZSS-Android/p/3968058.html
Copyright © 2020-2023  润新知