2016-10-12 4 views
0

문자열 유형의 페이로드 본문이있는 API가 있습니다. 그러나 페이로드 본문의 일부로 jsonimage (multiparty/form)이 모두 있습니다. 이런 식으로 뭔가가 :문자열 매개 변수가있는 다중 부분/양식 이미지를 android에 게시하는 방법

json={jsonbody} [email protected]/testing.png 

이 내가

public static String uploadImageQuery(Context context, String urlString, String method, 
             JSONObject jsonObject, Bitmap largeImageBitmap, 
             Dialog dialog) throws IOException { 

    String responseString = null; 
    HttpURLConnection conn = null; 
    URL url = new URL(urlString); 

    conn = (HttpURLConnection) url.openConnection(); 

    Log.d(TAG, "Uploading largeImageBitmap .."); 

    conn.setConnectTimeout((int) Constants.THREE_MINUTES); 
    conn.setDoOutput(true); 
    conn.setDoInput(true); 
    conn.setUseCaches(false); 
    conn.setRequestMethod(method); 
    conn.setChunkedStreamingMode(16 * 1024); 
    conn.setRequestProperty("Transfer-Encoding", "chunked"); 

    // The “boundry” can be any string. In this example it’s **********. 
    // It’s used in the body of the request to seperate each field being submitted. 
    //conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); 
    conn.setRequestProperty("Authorization", "Bearer " + access_token); 
    conn.connect(); 


    DataOutputStream dataOS = new DataOutputStream(conn.getOutputStream()); 
    dataOS.write(("json=" + jsonObject.toString()).getBytes(Constants.CHARSET_UTF_8)); 
    dataOS.write(("image=").getBytes(Constants.CHARSET_UTF_8)); 

    /* Standard order patten for sending multipart data*/ 
    dataOS.write(buildStartPayload().getBytes(Constants.CHARSET_UTF_8)); 
    dataOS.write(getImageBytes(largeImageBitmap)); 
    dataOS.write(buildEndPayload().getBytes(Constants.CHARSET_UTF_8)); 

    Log.d(TAG, "Posting String data to server : " + dataOS.toString()); 

    dataOS.flush(); 
    dataOS.close(); 

    // Ensure we got the HTTP 200 response code 
    int responseCode = conn.getResponseCode(); 
    String responseMessage = conn.getResponseMessage(); 
    Log.d(TAG, "Response code for upload image query : " + responseCode + " Message : " + responseMessage); 

    if (responseCode != 200) { 
     dialog.cancel(); 
     Log.e(TAG, String.format("Received the response code %d from the URL %s", responseCode, url)); 
     // DisplayMessage.error("Couldn't upload image. Please try again later.", activity); 
    } 

    // Read the response 
    InputStream is = conn.getInputStream(); 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    byte[] bytes = new byte[1024]; 
    int bytesRead; 
    while ((bytesRead = is.read(bytes)) != -1) { 
     baos.write(bytes, 0, bytesRead); 
    } 
    byte[] bytesReceived = baos.toByteArray(); 
    baos.close(); 
    is.close(); 

    String response = new String(bytesReceived); 
    Log.d(TAG, "Response:" + response); 

    conn.disconnect(); 
    conn = null; 
    Log.d(TAG, "Cleard the connection handle."); 

    return responseString; 
} 

private static String buildStartPayload() { 
    String contentDisposition = "Content-Disposition: form-data; name=\"testing\"; filename=\"testing.png\""; 
    String contentType = "Content-Type: image/png"; 

    // This is the standard format for a multipart request 
    StringBuilder requestBody = new StringBuilder(); 
    requestBody.append(LINE_START); 
    requestBody.append(BOUNDARY); 
    requestBody.append(LINE_END); 
    requestBody.append(contentDisposition); 
    requestBody.append(LINE_END); 
    requestBody.append(contentType); 
    requestBody.append(LINE_END); 
    requestBody.append(LINE_END); 
    return requestBody.toString(); 
} 

private static String buildEndPayload() { 
    // This is the standard format for a multipart request 
    StringBuilder requestBody = new StringBuilder(); 
    requestBody.append(LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END); 
    return requestBody.toString(); 
} 

현재 일을하고 나는 다중/폼 이미지를 게시하기 전에 HttpURLConnection을 사용하고 DataOutputform를 사용하여 그 일을 시도하지만 난 "나쁜 무엇입니까 무엇인가 요청 "오류가 발생했습니다. 도움이되는 도서관이 있습니까? 내가 발리 슛을 사용하지만 좋은 이미지를 지원하지 않습니다. 나는 개조를 시도하지 않았지만 지금 당장 가고 싶지 않다. 나는 이것이 HttpURLConnection을 사용하여 이루어지기를 희망한다.

+0

원한다면 문자열로 된 이미지는 Base 64 - https://www.base64-image.de/를 사용합니다. - 그런 다음 문자열 요청에 대해 Volley를 사용하지만 picasso와 같은 것을 사용하여 이미지 http : //를 처리한다는 의미는 아닙니다. square.github.io/picasso/ - 내가 사용하는 글은 글라이드 https://github.com/bumptech/glide를 사용할 수 있으며, 또 다른 인기있는 이미지는 유니버설 이미지 로더 https://github.com/nostra13/Android입니다. - Universal-Image-Loader – Tasos

+0

Gaurav에서 비트 맵을 64 진수로 인코딩 된 문자열로 변환하고 다른 매개 변수와 같은 형식으로 게시 할 수 있습니다. 서버 측에서는베이스 64를 받고 비트 맵으로 저장합니다. – Aakash

+0

서버 쪽이 내 통제하에 있지 않습니다. API를 통합하고 있으며 API에서 jpeg 형식의 이미지가 필요합니다. 중요한 문제는 API가 잘 정의되어 있지 않다는 것입니다. –

답변

0

문자열으로 인코딩 한 다음 문자열을 요청 본문에 삽입해야 할 수 있습니다.

StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response 
      .Listener<String>() { 
     @Override 
     public void onResponse(String response) { 
      Log.d(TAG, "onResponse() called with: response = [" + response + "]"); 
     } 
    }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      Log.d(TAG, "onErrorResponse() called with: error = [" + error + "]"); 
     } 
    }) { 
     @Override 
     protected Map<String, String> getParams() throws AuthFailureError { 
      Map<String, String> params = new HashMap<>(); 
      params.put("img", BASE64_IMG); 
      return params; 
     } 
    }; 
    mRequestQueue.add(stringRequest); 

재정의 getParams을하고 귀하의 요청에 PARAMS을 넣어 :

당신이 발리를 사용하는 경우, 당신이 시도 할 수 있습니다.

Base64을 사용하여 이미지를 문자열로 인코딩해야합니다.

+0

질문에서 언급 한 것처럼 서버는 base64 문자열이 아닌 다중 부분/양식 이미지를 기대합니다 –

0

당신은 ...

protected String doInBackground(Void... params) { 
      String result = ""; 
      try { 
       HttpClient client = new DefaultHttpClient(); 
       HttpPost post = new HttpPost("your url"); 
       post.setHeader("key", Key_for_XYZ); 

       MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); 
       entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); 
       entityBuilder.addTextBody("id", id); 
       entityBuilder.addTextBody("name", fnm); 
       // file path..... 
       entityBuilder.addBinaryBody("uploaded_file", destination); 

       cz.msebera.android.httpclient.HttpEntity entity = entityBuilder.build(); 
       post.setEntity(entity); 
       cz.msebera.android.httpclient.HttpResponse response = client.execute(post); 
       cz.msebera.android.httpclient.HttpEntity httpEntity = response.getEntity(); 
       result = EntityUtils.toString(httpEntity); 
       Log.e("result", result); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
      return result; 
     } 

// 당신이이 가져 오기를 패키지 한 확인이 라이브러리에 링크가 추가 이미지 click here..

compile "cz.msebera.android:httpclient:4.4.1.2" 

코드 사용할 수 있습니다

import cz.msebera.android.httpclient.client.HttpClient; 
import cz.msebera.android.httpclient.client.methods.HttpPost; 
import cz.msebera.android.httpclient.entity.mime.HttpMultipartMode; 
import cz.msebera.android.httpclient.entity.mime.MultipartEntityBuilder; 
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient; 
import cz.msebera.android.httpclient.util.EntityUtils; 
+0

본문에 이미지를 추가하는 위치는 어디입니까? 그리고 서버는 이미지를위한 멀티 파트/폼 –

+0

이미지를 제외하고 파일입니다. 당신은 새로운 파일 (경로) –

+0

으로 할 수 있습니다 비트 맵,하지만 거기에 이미지를 보내고 멀티/일부 예상 형식 –