2016-04-11 26 views
0

json-serverというダミーの残りのAPIサーバーを使用しています。私はサーバーにPOSt要求をすることができるアンドロイドアプリを書いた、サーバーは同様に201を返します。Android HTTPクライアントを使用してREST APIサーバーにファイルをアップロードする

私は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(); 
        } 
       } 
      } 

私はポストを行うたびに、新しいIdが残りAPIサーバー上にある私のJSONファイルにコメントアレーの下に追加された私のデバイスからファイルを送信したいです。

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

私はので、私は全体のテキストファイルの内容を送信することができます私のアンドロイドコードまたはREST APIポストURLを変更する方法がわからない、それは、サーバー上のJSONファイルに掲載されます。

+2

'localhost'? Androidデバイスのサーバーもですか? – greenapps

+0

'localhost'以外の問題は、サーバーがファイルのアップロードをサポートしていることをどのように知っていますか? –

+0

ローカルホストではなく、コードを更新しました。誰かがdownvoteを説明することはできますか?私はここの著者に同意する必要があります:https://medium.com/johnslegers/the-decline-of-stack-overflow-7cb69faa575d#.cb8mr39l6 – nitinsh99

答えて

4

はコメントを行い、あなたがどんな困難を見つけた場合、これを使用して、このコードは完璧に動作

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!! 
+0

ありがとうございますArpit、私はちょっとあなたのコードを微調整し、今すぐ私のファイルを送信することができます。 – nitinsh99

+0

お手数をおかけしますが、できれば投票してください。 –

関連する問題