2014-09-30 37 views
-1

我想知道是否有可能發送一個非常非常大的字符串使用多部分請求到服務器。是否可以將字符串轉換爲File對象,反之亦然,因爲我可以通過多部分請求發送圖像,但作爲File。如何通過多部分請求發送字符串?Android發送巨大的字符串作爲多部分到服務器

將字符串轉換爲字節並上傳後。我如何檢索文件並將其轉換爲字符串?

回答

2

你有這樣

public void connectForMultipart() throws Exception { 
    con = (HttpURLConnection) (new URL(url)).openConnection(); 
    con.setRequestMethod("POST"); 
    con.setDoInput(true); 
    con.setDoOutput(true); 
    con.setRequestProperty("Connection", "Keep-Alive"); 
    con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); 
    con.connect(); 
    os = con.getOutputStream(); 
} 

public void addFormPart(String paramName, String value) throws Exception { 
    writeParamData(paramName, value); 
} 

public void addFilePart(String paramName, String fileName, byte[] data) throws Exception { 
    os.write((delimiter + boundary + "\r\n").getBytes()); 
    os.write(("Content-Disposition: form-data; name=\"" + paramName + "\"; filename=\"" + fileName + "\"\r\n" ).getBytes()); 
    os.write(("Content-Type: application/octet-stream\r\n" ).getBytes()); 
    os.write(("Content-Transfer-Encoding: binary\r\n" ).getBytes()); 
    os.write("\r\n".getBytes()); 

    os.write(data); 

    os.write("\r\n".getBytes()); 
} 
public void finishMultipart() throws Exception { 
    os.write((delimiter + boundary + delimiter + "\r\n").getBytes()); 
} 

更新

工作爲獲得響應

httpPost.setEntity(entity); 
HttpResponse response = httpClient.execute(httpPost); 

BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); 



String sResponse; 
while ((sResponse = reader.readLine()) != null) 
{ 
    s = s.append(sResponse); 
} 

if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) 
{ 
    return s.toString(); 
}else 
{ 
    return "{\"status\":\"false\",\"message\":\"Some error occurred\"}"; 
} 
} catch (Exception e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

代替圖像,你可以發送任何東西,你想.. 。如果它創建了一些,然後 你應該把大文件分成小部分,然後嘗試發送並在服務器上加入這個小部分。

+0

你沒有告訴如何檢索字符串。我如何檢索字符串?我如何檢索請求作爲字符串? – migs 2014-09-30 12:46:08

+0

請檢查我的更新回答:) – Gattsu 2014-09-30 12:49:22

+0

你怎麼知道'response.getEntity()。getContent()'會在'addFilePart'中返回'data',而不是'addFormPart'中的'value'? – migs 2014-09-30 13:36:17

相關問題