2011-10-19 99 views
1

我需要一點幫助,從我的Android應用程序發送HttpUrlConnection。直到現在,我正在做這個基本Http Client。但問題是,當我從服務器收到一個大流時,我的應用程序崩潰了outofmemory異常。這就是爲什麼我做了一項研究,並發現HttpUrlConnection讓我能夠把這個流變成一個片斷。那麼有人可以幫我發一些參數,並從服務器獲得響應嗎?android HttpUrlConnection發送帖子和參數獲取請求

,我用上面的代碼是這樣的:

   httpclient = new DefaultHttpClient(); 
       httppost = new HttpPost("http://www.rpc.your_nightmare.com"); 

       TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); 
       String deviceId = tm.getDeviceId(); 
       String resolution = Integer.toString(getWindow().getWindowManager().getDefaultDisplay().getWidth())+ "x" + 
              Integer.toString(getWindow().getWindowManager().getDefaultDisplay().getHeight()); 
       String version = "Android " + Build.VERSION.RELEASE; 
       String locale = getResources().getConfiguration().locale.toString(); 
       String clientApiVersion = null; 

       PackageManager pm = this.getPackageManager(); 
       PackageInfo packageInfo = pm.getPackageInfo(this.getPackageName(), 0); 
       clientApiVersion = packageInfo.versionName; 

       hash = getAuthHash(); 

       String timestampSQL = "SELECT dbTimestamp FROM users"; 
       Cursor cursor = systemDbHelper.executeSQLQuery(timestampSQL); 
       if(cursor.getCount()==0){ 
        Log.i("Cursor","TimeStamp Cursor Empty!"); 
       } else if(cursor.getCount()>0){ 
        cursor.moveToFirst(); 
        timeStamp = cursor.getString(cursor.getColumnIndex("dbTimestamp")); 
       } 

       TelephonyManager tMgr =(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE); 
       phoneNumber = tMgr.getLine1Number(); 
       Log.i("Phone","Phone Number : "+phoneNumber); 

       postParameters = new ArrayList<NameValuePair>(); 
       postParameters.add(new BasicNameValuePair("debug_data","1")); 
       postParameters.add(new BasicNameValuePair("client_auth_hash", hash)); 
       postParameters.add(new BasicNameValuePair("timestamp", timeStamp)); 
       postParameters.add(new BasicNameValuePair("mobile_phone", phoneNumber)); 
       postParameters.add(new BasicNameValuePair("deactivate_collections",Integer.toString(index))); 
       postParameters.add(new BasicNameValuePair("client_api_ver", clientApiVersion)); 
       postParameters.add(new BasicNameValuePair("set_locale", locale)); 
       postParameters.add(new BasicNameValuePair("device_os_type", version)); 
       postParameters.add(new BasicNameValuePair("device_sync_type", "14")); 
       postParameters.add(new BasicNameValuePair("device_identification_string", version)); 
       postParameters.add(new BasicNameValuePair("device_identificator", deviceId)); 
       postParameters.add(new BasicNameValuePair("device_resolution", resolution)); 

       httppost.setEntity(new UrlEncodedFormEntity(postParameters)); 

       HttpResponse response = httpclient.execute(httppost); 
       Log.w("Response ","Status line : "+ response.getStatusLine().toString()); 

       HttpEntity entity = response.getEntity(); 
       InputStream stream2 = entity.getContent(); 


       int nRead; 
       byte[] data = new byte[8*1024]; 

       while ((nRead = stream2.read(data, 0, data.length)) != -1) { 
        buffer.write(data, 0, nRead); 
       } 

       buffer.flush(); 
       return buffer.toByteArray(); 

,比處理它是這樣的:

InputStream stream = new ByteArrayInputStream(buffer, 0, temp.length); 
Log.i("Temp","Temp : "+temp.length); 
Log.i("index","index : "+index); 
responseBody = convertStreamToString(stream); 
Log.i("responseBody","responseBody : "+responseBody); 
//calculations 
+0

我看你仍然面臨同樣的問題,所以我認爲你錯過了某些東西我們提前提供或者錯誤地使用它。所以你可以提供完整的代碼,以便我們檢查它。你在嘗試什麼。 – user370305

+1

問題是響應太大,我無法將其轉換爲字符串並解析它。我需要找到一種方法來將它分解成碎片,並且正如我在android文檔中看到的那樣,httpurlconnection是一種更好的方法來完成這項工作,但對於瞭解如何發佈同步參數等,有點困難。 –

+0

多少反應很大?有很多人正在使用與我們建議的服務器響應相同的技術。 – user370305

回答

0

這裏是你可以用HttpURLConnecion做出網絡連接的方式服務器:

 System.setProperty("http.keepAlive", "false"); 
     connection = (HttpURLConnection) new URL(url).openConnection(); 
     connection.setDoOutput(true); 
     connection.setConnectTimeout(5000); // miliseconds 
     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("Connection", "Keep-Alive"); 
     connection.setRequestProperty("Charset", charset); 
     connection.setRequestProperty("Content-Type", 
       "application/x-www-form-urlencoded;charset=" + charset); 
     OutputStream output = null; 
     try { 
      output = connection.getOutputStream(); 
      output.write(query.getBytes(charset)); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      if (output != null) 
       try { 
        output.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
     } 

     int status = ((HttpURLConnection) connection).getResponseCode(); 
     Log.d("", "Status : " + status); 

     for (Entry<String, List<String>> header : connection 
       .getHeaderFields().entrySet()) { 
      Log.d("Headers", 
        "Headers : " + header.getKey() + "=" 
          + header.getValue()); 
     } 

     InputStream response = new BufferedInputStream(
       connection.getInputStream()); 

     int bytesRead = -1; 
     byte[] buffer = new byte[30 * 1024]; 
     while ((bytesRead = response.read(buffer)) > 0 && stopThread) { 
      byte[] buffer2 = new byte[bytesRead]; 
      System.arraycopy(buffer, 0, buffer2, 0, bytesRead); 
      // buffer2 is you chunked response 
     } 
     connection.disconnect(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 

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