使用Android HTTP客户端将文件上载到REST api服务器

时间:2016-04-11 15:13:27

标签: android rest httpclient

我正在使用名为json-server的虚拟休息API服务器。我写了一个Android应用程序,它能够向服务器发出POSt请求,服务器也返回预期的201。

我对REST api不太熟悉。我想从我的设备发送文件

     public void run() {
                    Logger.d("reponse","inside thread");

                    HttpClient client = new DefaultHttpClient(TunnelView.this);
                    String url = "http://some_server:3000/comments";
                    HttpGet get = new HttpGet(url);
                    HttpPost post = new HttpPost(url);
                    HttpResponse response = null;
                    post.setEntity(new FileEntity(new File("/root/sdcard/Download/File.txt"),"application/octect-stream"));
                    try
                    {
                        response = client.execute(post);
                        String res = response.getEntity().getContent().toString();
                        Logger.d("response", res);




                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            }

每次发帖时,都会在位于其余API服务器上的json文件的Comments数组下添加新ID。

  "comments": [
{
  "id": 1,
  "body": "some comment",
  "postId": 1
},
{
  "id": 2
},]

我不知道如何更改我的Android代码或REST API Post URl,因此我可以发送整个文本文件内容,并将其发布到服务器上的json文件中。

1 个答案:

答案 0 :(得分:3)

试试这个

    public static JSONObject postFile(String url,String filePath,int id){
    String result="";
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    File file = new File(filePath);
    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "image/jpeg");
    StringBody stringBody= null;
    JSONObject responseObject=null;
    try {
        stringBody = new StringBody(id+"");
        mpEntity.addPart("file", cbFile);
        mpEntity.addPart("id",stringBody);
        httpPost.setEntity(mpEntity);
        System.out.println("executing request " + httpPost.getRequestLine());
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity resEntity = response.getEntity();
        result=resEntity.toString();
        responseObject=new JSONObject(result);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return responseObject;
}

此代码完美运行,使用此代码,如果您发现任何困难,请进行评论。

 Happy coding!!
相关问题