2016-05-28 9 views
0

カメラの携帯電話で撮影した写真をIMAGGAというREST APIにアップロードする必要があります。このコードは私に識別子を与えるので、私は画像のタグ付けからJSONを取得するために使用することができAndroid StudioでHttpURLConnectionを使用して画像をアップロードする(

String apiKey = "", 
apiSecret = ""; 


HttpResponse response = Unirest.post("https://api.imagga.com/v1/content") 
.basicAuth(apiKey, apiSecret) 
.field("image", new File("/path/to/image.jpg")) 
.asJson(); 

JSONObject jsonResponse = response.getBody().getObject(); 
System.out.println(jsonResponse.toString()); 

:私はAPI'sドキュメント次のJavaコードで見つかりました。

私はHttpURLConnectionを使用しているため、完了できません。どうすればいいのかわかりません。

.field("image", new File("/path/to/image.jpg")) 
+0

問題はどのようなものですか? – greenapps

答えて

1

は以下postImageToImaggaメソッドを使用し、Imaggaに画像を投稿する:私は問題を抱えている

唯一のものはアップロード一部です。

を行うには:connection.setRequestProperty("Authorization", "<insert your own Authorization e.g. Basic YWNjX>");


public String postImageToImagga(String filepath) throws Exception { 
    HttpURLConnection connection = null; 
    DataOutputStream outputStream = null; 
    InputStream inputStream = null; 

    String twoHyphens = "--"; 
    String boundary = "*****"+Long.toString(System.currentTimeMillis())+"*****"; 
    String lineEnd = "\r\n"; 

    int bytesRead, bytesAvailable, bufferSize; 
    byte[] buffer; 
    int maxBufferSize = 1*1024*1024; 

    String filefield = "image"; 

    String[] q = filepath.split("/"); 
    int idx = q.length - 1; 

    File file = new File(filepath); 
    FileInputStream fileInputStream = new FileInputStream(file); 

    URL url = new URL("https://api.imagga.com/v1/content"); 
    connection = (HttpURLConnection) url.openConnection(); 

    connection.setDoInput(true); 
    connection.setDoOutput(true); 
    connection.setUseCaches(false); 

    connection.setRequestMethod("POST"); 
    connection.setRequestProperty("Connection", "Keep-Alive"); 
    connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0"); 
    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary); 
    connection.setRequestProperty("Authorization", "<insert your own Authorization e.g. Basic YWNjX>"); 

    outputStream = new DataOutputStream(connection.getOutputStream()); 
    outputStream.writeBytes(twoHyphens + boundary + lineEnd); 
    outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] +"\"" + lineEnd); 
    outputStream.writeBytes("Content-Type: image/jpeg" + lineEnd); 
    outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); 
    outputStream.writeBytes(lineEnd); 

    bytesAvailable = fileInputStream.available(); 
    bufferSize = Math.min(bytesAvailable, maxBufferSize); 
    buffer = new byte[bufferSize]; 

    bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
    while(bytesRead > 0) { 
     outputStream.write(buffer, 0, bufferSize); 
     bytesAvailable = fileInputStream.available(); 
     bufferSize = Math.min(bytesAvailable, maxBufferSize); 
     bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
    } 

    outputStream.writeBytes(lineEnd); 
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 

    inputStream = connection.getInputStream(); 

    int status = connection.getResponseCode(); 
    if (status == HttpURLConnection.HTTP_OK) { 
     BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
     String inputLine; 
     StringBuffer response = new StringBuffer(); 

     while ((inputLine = in.readLine()) != null) { 
      response.append(inputLine); 
     } 

     inputStream.close(); 
     connection.disconnect(); 
     fileInputStream.close(); 
     outputStream.flush(); 
     outputStream.close(); 

     return response.toString(); 
    } else { 
     throw new Exception("Non ok response returned"); 
    } 
} 

  1. コードに次の行を参照して、Imaggaダッシュボードからのコードで独自の基本認証の詳細を挿入してください上記のコードをUI以外のスレッドで呼び出すには、AsyncTask

    public class PostImageToImaggaAsync extends AsyncTask<Void, Void, Void> { 
    
        @Override 
        protected void onPreExecute() { 
        } 
    
        @Override 
        protected Void doInBackground(Void... params) { 
         try { 
          String response = postImageToImagga("/mnt/sdcard/Pictures/Stone.jpg"); 
          Log.i("imagga", response); 
         } catch (Exception e) { 
    
         } 
         return null; 
        } 
    
        @Override 
        protected void onPostExecute(Void result) { 
        } 
    } 
    

    上記PostImageToImaggaAsyncコードを呼び出すには:

    PostImageToImaggaAsync postImageToImaggaAsync = new PostImageToImaggaAsync(); 
    postImageToImaggaAsync.execute(); 
    
+0

ありがとうございます!それは実際に動作します!!!! – Viclpk

関連する問題