【问题标题】:JSON POST request for download image from server in android从android中的服务器下载图像的JSON POST请求
【发布时间】:2014-04-07 00:41:21
【问题描述】:

我需要下载图像并将其设置为 imageview 。对于解析,我使用 JSON POST request ,为此我使用 base64 。我得到了base64 类型的数据以记录image 标记,但问题是如何分离image 的值并将其转换为string,然后将其显示到列表视图中?如果不使用base64 显示图像,还有其他方法,请建议我们。

为了解析数据,我使用 JSON parserHttpPost 。 现在如何从我在混淆上方显示的响应JSON 格式中获取image 的值??

提前谢谢..

【问题讨论】:

  • 从哪里获取图像?
  • 即 RESPONSE JSON 格式 { "root": { "response": { "message": { "type": "success", "message": "Success." },“数据”:{“图像”:[{“web_id”:“1”,“blob_image”:“image_content”}],“last_synchronized_date”:“2014-03-03 13:32:31”}}} }
  • @anuruddhika:我在 logcat 中获得了 base64 格式的图像
  • 那是我的日志:响应:{"root":{"response":{"message":{"type":"success","message":"SUCCESS"},"data ":{"image":"\/9j\/4AAQSkZJRgABAQEASABIAAD\/4QDkRXhpZgAASUkqAAgAAAAIABIBAwABAAAAAQAAABoBBQABAAAAbgAAABsBBQABAAAAdgAAACgBAwABAAAAAgAAADEBAgAcAAAAfgAAADIB @anuruddhika
  • 你可以试试我的回答。通常我使用该方法从 JSON 加载图像。 image_location 必须是您的 JSON 输出 url。试试吧。 :)

标签: android post image-uploading


【解决方案1】:

你可以这样做。

在服务器中创建文件夹。将图像放在该文件夹中。获取图像的 URL 并插入到数据库中。 然后获取该 url 的 JSON 值 添加此方法并将该 url 传递给此方法。

Bitmap bitmap;
    void loadImage(String image_location) {

        URL imageURL = null;

        try {
            imageURL = new URL(image_location);
        }

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

        try {
            HttpURLConnection connection = (HttpURLConnection) imageURL
                    .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream inputStream = connection.getInputStream();

            bitmap = BitmapFactory.decodeStream(inputStream);// Convert to
                                                                // bitmap
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {

            e.printStackTrace();
        }


       }

【讨论】:

  • 我肯定会应用它。感谢您的积极响应,如果您认为这个问题很重要,请点击。谢谢..
  • 没问题。我之前遇到过这个问题。这就是我这样做的原因。
  • 不客气。你为什么不接受我的回答。请作为答案。快乐的代码。 :)
【解决方案2】:

试试下面的代码:

JSONObject res = jsonObj.getJSONObject("root");
JSONObject data = jsonObj.getJSONObject("data");
JSONArray imgs= jsonObj.getJSONArray ("images");

for(int i=0;i<imgs.length();i++){
    JSONObject Ldetails = Ldtls.getJSONObject(i);
    String img= Ldetails.getString("image");

   byte[] decodedString = Base64.decode(img,Base64.NO_WRAP);
   InputStream inputStream  = new ByteArrayInputStream(decodedString);
   Bitmap bitmap  = BitmapFactory.decodeStream(inputStream);
   imagevw.setImageBitmap(bitmap);

}

imagevw 是你的 ImageView。

【讨论】:

    【解决方案3】:

    使用 Gson Parser,然后将 base64 图像字符串解析为字节数组并应用于图像。

    您的模型类如下:

    public class JsonWrapper
    {
        private Root root ;
        public Root getroot()
        {
            return this.root;
        }
        public void setroot(Root root)
        {
            this.root = root;
        }
    }
    
    
    
    
    
    public class Root
    {
        private Response response ;
        public Response getresponse()
        {
            return this.response;
        }
        public void setresponse(Response response)
        {
            this.response = response;
        }
    }
    
    
    
    public class Response
    {
        private Message message ;
        public Message getmessage()
        {
            return this.message;
        }
        public void setmessage(Message message)
        {
            this.message = message;
        }
        private Data data ;
        public Data getdata()
        {
            return this.data;
        }
        public void setdata(Data data)
        {
            this.data = data;
        }
    }
    
    public class Message
    {
        private String type ;
        public String gettype()
        {
            return this.type;
        }
        public void settype(String type)
        {
            this.type = type;
        }
        private String message ;
        public String getmessage()
        {
            return this.message;
        }
        public void setmessage(String message)
        {
            this.message = message;
        }
    }
    
    import java.util.ArrayList;
    
    
    public class Data
    {
        private ArrayList<Image> images ;
        public ArrayList<Image> getimages()
        {
            return this.images;
        }
        public void setimages(ArrayList<Image> images)
        {
            this.images = images;
        }
        private String last_synchronized_date ;
        public String getlast_synchronized_date()
        {
            return this.last_synchronized_date;
        }
        public void setlast_synchronized_date(String last_synchronized_date)
        {
            this.last_synchronized_date = last_synchronized_date;
        }
    }
    
    public class Image
    {
        private String web_id ;
        public String getweb_id()
        {
            return this.web_id;
        }
        public void setweb_id(String web_id)
        {
            this.web_id = web_id;
        }
        private String blob_image ;
        public String getblob_image()
        {
            return this.blob_image;
        }
        public void setblob_image(String blob_image)
        {
            this.blob_image = blob_image;
        }
    }
    

    使用 Gson 解析 json 后,如下所示:

    JsonWrapper jsonWrapper = new JsonWrapper();
    Gson gsonParser = new Gson();
    jsonWrapper = gsonParser.fromJson(data, jsonWrapper.getClass());
    

    接下来您可以遍历所有图像

    ArrayList<Image> images = jsoinWrapper.getRoot().getResponse().getData().getImages();
    
    for(Image image : images)
    {
      byte[] decodedString = Base64.decode(image.getblob_image(), Base64.DEFAULT);
                    Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
    
    if (decodedString != null) {
                        imageViewtype.setImageBitmap(decodedByte);
                    }
    
    }
    

    【讨论】:

      【解决方案4】:
      public class SingleContactActivity extends Activity implements OnClickListener {
      
      private static final String TAG_ImageList = "CatList";
      private static final String TAG_ImageID = "ID";
      private static final String TAG_ImageUrl = "Name";
      
      private static String url_MultiImage;
      TextView uid, pid;
      JSONArray contacts = null;
      private ProgressDialog pDialog;
      String details;
      // String imagepath = "http://test2.sonasys.net/Content/WallPost/b3.jpg";
      String imagepath = "";
      String imagepath2;
      Bitmap bitmap;
      ImageView image;
      SessionManager session;
      TextView myprofileId;
      
      TextView pending;
      TextView Categories, visibleTo;
      int count = 0;
      ImageButton btn;
      
      // -----------------------
      ArrayList<HashMap<String, String>> ImageList;
      JSONArray JsonArray = null;
      
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_single_contact);
      
          url_MultiImage = "http://test2.sonasys.net/Android/GetpostImg?UserID=1&PostId=80";
      
          new MultiImagePath().execute();
      
          ImageList = new ArrayList<HashMap<String, String>>();
      
      }
      
      private class MultiImagePath extends AsyncTask<Void, Void, Void> {
          @Override
          protected void onPreExecute() {
              super.onPreExecute();
      
          }
      
          @Override
          protected Void doInBackground(Void... params) {
              // TODO Auto-generated method stub
      
              // Creating service handler class instance
              ServiceHandler sh = new ServiceHandler();
      
              // Making a request to url and getting response
              String jsonStr = sh.makeServiceCall(url_MultiImage,
                      ServiceHandler.GET);
      
              Log.d("Response: ", "> " + jsonStr);
      
              if (jsonStr != null) {
                  try {
                      JSONObject jsonObj = new JSONObject(jsonStr);
      
                      // Getting JSON Array node
                      JsonArray = jsonObj.getJSONArray(TAG_ImageList);
                      if (JsonArray.length() != 0) {
      
                          for (int i = 0; i < JsonArray.length(); i++) {
                              JSONObject c = JsonArray.getJSONObject(i);
      
                              String Img_ID = c.getString(TAG_ImageID);
                              String Img_Url = c.getString(TAG_ImageUrl);
      
                              // tmp hashmap for single contact
                              HashMap<String, String> contact = new HashMap<String, String>();
      
                              // adding each child node to HashMap key => value
                              contact.put(TAG_ImageID, Img_ID);
                              contact.put(TAG_ImageUrl, Img_Url);
      
                              // adding contact to contact list
                              ImageList.add(contact);
                          }
                      }
                      Log.e("JsonLength", "length is ZERO");
      
                  } catch (JSONException e) {
                      e.printStackTrace();
                  }
              } else {
                  Log.e("ServiceHandler", "Couldn't get any data from the url");
              }
      
              return null;
          }
      
          @Override
          protected void onPostExecute(Void result) {
              super.onPostExecute(result);
      
              AutoGenImgBtn();
      
          }
      
      }
      
      @SuppressWarnings("deprecation")
      public void AutoGenImgBtn() {
      
          int count = ImageList.size();
          LinearLayout llimage = (LinearLayout) findViewById(R.id.llimage);
      
          ImageButton[] btn = new ImageButton[count];
          for (int i = 0; i < count; i++) {
              btn[i] = new ImageButton(this);
      
              btn[i].setId(Integer.parseInt(ImageList.get(i).get(TAG_ImageID)));
              btn[i].setOnClickListener(this);
              btn[i].setTag("" + ImageList.get(i).get(TAG_ImageUrl));
      
              btn[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                      LayoutParams.WRAP_CONTENT));
              btn[i].setImageDrawable(getResources().getDrawable(drawable.di1));
              btn[i].setAdjustViewBounds(true);
      
              // btn[i].setTextColor(getResources().getColor(color.white));
      
              llimage.addView(btn[i]);
      
          }
      
      }
      
      @SuppressWarnings("deprecation")
      @Override
      public void onClick(View v) {
          // TODO Auto-generated method stub
      
          btn = (ImageButton) v;
          String s = btn.getTag().toString();
      
          new ImageDownloader().execute(s);
      
      }
      
      private class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
      
          @Override
          protected Bitmap doInBackground(String... param) {
              // TODO Auto-generated method stub
              return downloadBitmap(param[0]);
          }
      
          @Override
          protected void onPreExecute() {
              Log.i("Async-Example", "onPreExecute Called");
              pDialog = new ProgressDialog(SingleContactActivity.this);
              pDialog.setMessage("Loading...");
              pDialog.setCancelable(true);
              pDialog.setTitle("In progress...");
              // pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
              pDialog.setIcon(android.R.drawable.stat_sys_download);
              pDialog.setMax(100);
              // pDialog.setTitle("Post Details");
              pDialog.show();
      
          }
      
          @Override
          protected void onPostExecute(Bitmap result) {
              Log.i("Async-Example", "onPostExecute Called");
      
              if (bitmap != null) {
                  btn.setImageBitmap(bitmap);
      
              }
      
              if (pDialog.isShowing())
                  pDialog.dismiss();
      
          }
      
          private Bitmap downloadBitmap(String url) {
              // initilize the default HTTP client object
              final DefaultHttpClient client = new DefaultHttpClient();
      
              // forming a HttoGet request
              final HttpGet getRequest = new HttpGet(url);
              try {
      
                  HttpResponse response = client.execute(getRequest);
      
                  // check 200 OK for success
                  final int statusCode = response.getStatusLine().getStatusCode();
      
                  if (statusCode != HttpStatus.SC_OK) {
                      Log.w("ImageDownloader", "Error " + statusCode
                              + " while retrieving bitmap from " + url);
                      return null;
      
                  }
      
                  final HttpEntity entity = response.getEntity();
                  if (entity != null) {
                      InputStream inputStream = null;
                      try {
                          // getting contents from the stream
                          inputStream = entity.getContent();
      
                          // decoding stream data back into image Bitmap that
                          // android understands
                          bitmap = BitmapFactory.decodeStream(inputStream);
      
                          return bitmap;
                      } finally {
                          if (inputStream != null) {
                              inputStream.close();
                          }
                          entity.consumeContent();
                      }
                  }
              } catch (Exception e) {
                  // You Could provide a more explicit error message for
                  // IOException
                  getRequest.abort();
                  Log.e("ImageDownloader", "Something went wrong while"
                          + " retrieving bitmap from " + url + e.toString());
              }
      
              return null;
          }
      }
      
      
      
        #  Add Service Handler Class#
      
       public class ServiceHandler {
      
      static String response = null;
      public final static int GET = 1;
      public final static int POST = 2;
      
      public ServiceHandler() {
      
      }
      
      /*
       * Making service call
       * @url - url to make request
       * @method - http request method
       * */
      public String makeServiceCall(String url, int method) {
      
      
      
          return this.makeServiceCall(url, method, null);
      }
      
      /*
       * Making service call
       * @url - url to make request
       * @method - http request method
       * @params - http request params
       * 
      
       * */
      
      public String makeServiceCall(String url, int method,List<NameValuePair> params) {
      
          try {
              // http client
      
              DefaultHttpClient httpClient = new DefaultHttpClient();
              HttpEntity httpEntity = null;
              HttpResponse httpResponse = null;
      
              // Checking http request method type
              if (method == POST) {
                  HttpPost httpPost = new HttpPost(url);
                  // adding post params
                  if (params != null) {               
                      httpPost.setEntity(new UrlEncodedFormEntity(params));
      
                  }
      
                  httpResponse = httpClient.execute(httpPost);
      
              } else if (method == GET) {
                  // appending params to url
                  if (params != null) {
                      String paramString = URLEncodedUtils.format(params, "utf-8");
                      url += "?" + paramString;
                  }
                  HttpGet httpGet = new HttpGet(url);
      
                  httpResponse = httpClient.execute(httpGet);
      
              }
              httpEntity = httpResponse.getEntity();
              response = EntityUtils.toString(httpEntity);
      
          } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
          } catch (ClientProtocolException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
      
          return response;
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-17
        • 1970-01-01
        • 1970-01-01
        • 2015-09-10
        • 2012-09-22
        • 1970-01-01
        • 1970-01-01
        • 2016-01-21
        相关资源
        最近更新 更多