private void putImageInformation() { HttpURLConnection httpUrlConnection = null; try { httpUrlConnection = (HttpURLConnection) new URL(Constants.IMAGES_URL + "/" + suggestedImage.getBlobUrl()).openConnection(); httpUrlConnection.setRequestMethod("PUT"); httpUrlConnection.setRequestProperty("Content-Type", "application/json"); DataOutputStream wr = new DataOutputStream(httpUrlConnection.getOutputStream()); JSONObject jsonParam = new JSONObject(); jsonParam.put(ServerSharedConstants.LINK, suggestedImage.getLink()); jsonParam.put(ServerSharedConstants.SITE_LINK, suggestedImage.getSiteLink()); jsonParam.put(ServerSharedConstants.TAG, new JSONObject(suggestedImage.getTags())); jsonParam.put(ServerSharedConstants.KEY_WORDS, new JSONArray(suggestedImage.getKeyWords())); jsonParam.put(ServerSharedConstants.PHONE_NUMBER, messageItem.getFrom()); wr.writeBytes(jsonParam.toString()); wr.flush(); wr.close(); switch (httpUrlConnection.getResponseCode()) { case HttpURLConnection.HTTP_OK: InputStream in = new BufferedInputStream(httpUrlConnection.getInputStream()); break; case HttpURLConnection.HTTP_NOT_FOUND: InputStream err = new BufferedInputStream(httpUrlConnection.getErrorStream()); break; } } catch (MalformedURLException exception) { Log.e(TAG, "MalformedURLException"); } catch (IOException exception) { Log.e(TAG, "IOException"); } catch (JSONException e) { e.printStackTrace(); } finally { if (null != httpUrlConnection) httpUrlConnection.disconnect(); } }
private String uploadImage(String imgUploadURL) { String imgURL = ""; OkHttpClient client = new OkHttpClient(); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart( "file", "image.png", RequestBody.create( MediaType.parse("image/png"), new File(messageItem.getLocalResource()))) .addFormDataPart("title", "My photo") .build(); Request request = new Request.Builder().url(imgUploadURL).post(requestBody).build(); try { Response response = client.newCall(request).execute(); imgURL = response.body().string(); Log.d("response", "uploadImage:" + imgURL); } catch (IOException e) { e.printStackTrace(); } return imgURL; }
@Override protected void onPostExecute(String imgURL) { messageItem.setMsg(imgURL); new SendMessageTask(mContext, messageItem).execute(); }