SORU
1 AĞUSTOS 2012, ÇARŞAMBA


Gönderen HttpURLConnection ile POST kullanarak dosyaları

Beri Android geliştiriciler recommend kullanmak HttpURLConnection sınıf, merak ediyordum da herkes sağlayabilir benimle iyi bir örnek üzerinde nasıl bir bitmap "dosya" (aslında bir hafıza stream) SONRASI için bir Apache HTTP Sunucusu. Kurabiye ya da kimlik ya da bir şey karmaşık ilgilenmiyorum, ama ben sadece güvenilir ve mantık bir uygulama var. Burada gördüğüm tüm örneklerde daha fazla gibi görünüyor "bunu deneyelim belki çalışır".

Şu anda bu kod var:

URL url;
HttpURLConnection urlConnection = null;
try {
    url = new URL("http://example.com/server.cgi");

    urlConnection = (HttpURLConnection) url.openConnection();

} catch (Exception e) {
    this.showDialog(getApplicationContext(), e.getMessage());
}
finally {
    if (urlConnection != null)
    {
        urlConnection.disconnect();
    }
}

showDialog sadece AlertDialog (geçersiz bir URL durumda?) göstermek gerekir.

Şimdi, diyelim ki böyle bir bitmap oluşturmak olduğu ki: bir kontrol View türetilen ve posta ile göndermek istiyorum içinde Bitmap image = this.getBitmap(). Böyle bir şey elde etmek için uygun prosedür ne olacak? Sınıfları kullanmak için ne yapmak gerekiyor? this example gibi HttpPost kullanabilir miyim? Eğer öyleyse, nasıl benim bitmap InputStreamEntity inşa miyim? Bu iğrenç ilk aygıtta bir dosya bit eşlem saklamak için gerekli buluyorum.


Ayrıca gerçekten sunucu için orijinal bitmap her piksel değişmeden göndermeniz gerekiyor bahsetmeliyiz, JPEG dönüştürmek istemiyorum.

CEVAP
6 AĞUSTOS 2012, PAZARTESİ


HttpURLConnection sınıf dosya sarıcı elle oluşturmak zorunda kalmadan dosya göndermek için herhangi bir araç sağlamaz neden hiçbir fikrim yok. Buraya kadar ben de yapıyordum, ama eğer birisi daha iyi bir çözüm bilen varsa, lütfen bana bildirin.

Giriş verileri:

Bitmap bitmap = myView.getBitmap();

Statik şeyler:

String attachmentName = "bitmap";
String attachmentFileName = "bitmap.bmp";
String crlf = "\r\n";
String twoHyphens = "--";
String boundary =  "*****";

Talep kurulum:

HttpURLConnection httpUrlConnection = null;
URL url = new URL("http://example.com/server.cgi");
httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setDoOutput(true);

httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");
httpUrlConnection.setRequestProperty("Cache-Control", "no-cache");
httpUrlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary="   this.boundary);

İçerik sarıcı

DataOutputStream request = new DataOutputStream(httpUrlConnection.getOutputStream());

request.writeBytes(this.twoHyphens   this.boundary   this.crlf);
request.writeBytes("Content-Disposition: form-data; name=\""   this.attachmentName   "\";filename=\""   this.attachmentFileName   "\""   this.crlf);
request.writeBytes(this.crlf);

ByteBuffer 23 *dönüştürün

//I want to send only 8 bit black & white bitmaps
byte[] pixels = new byte[bitmap.getWidth() * bitmap.getHeight()];
for (int i = 0; i < bitmap.getWidth();   i) {
    for (int j = 0; j < bitmap.getHeight();   j) {
        //we're interested only in the MSB of the first byte, 
        //since the other 3 bytes are identical for B&W images
        pixels[i   j] = (byte) ((bitmap.getPixel(i, j) & 0x80) >> 7);
    }
}

request.write(pixels);

Son içerik sarıcı:

request.writeBytes(this.crlf);
request.writeBytes(this.twoHyphens   this.boundary   this.twoHyphens   this.crlf);

Floş çıkış arabelleği:

request.flush();
request.close();

Alın cevabı:

InputStream responseStream = new BufferedInputStream(httpUrlConnection.getInputStream());

BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
String line = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = responseStreamReader.readLine()) != null)
{
    stringBuilder.append(line).append("\n");
}
responseStreamReader.close();

String response = stringBuilder.toString();

Yakın yanıt yayını:

responseStream.close();

Yakın bağlantı:

httpUrlConnection.disconnect();

PS: ana iş parçacığı üzerinde Ağ istekleri için değil, çünkü tabii ki Android platformu mutlu etmek için private class AsyncUploadBitmaps extends AsyncTask<Bitmap, Void, String>, istek sarmak zorunda kaldım.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • majesticdubstep

    majesticdubs

    3 Kasım 2011
  • Marques Brownlee

    Marques Brow

    21 Mart 2008
  • RocketJump

    RocketJump

    22 ŞUBAT 2006