Android将巨大的字符串作为multipart发送到服务器

时间:2014-09-30 12:37:34

标签: android httpurlconnection multipart

我想知道是否可以使用多部分请求向服务器发送非常非常大的字符串。是否可以将字符串转换为File对象,反之亦然,因为我可以通过多部分请求发送图像,但作为File。如何通过多部分请求发送字符串?

将字符串转换为字节并上传后。如何检索文件并将其转换为字符串?

1 个答案:

答案 0 :(得分: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();
}

代替图像你可以发送任何东西,你想...如果它创造了一些麻烦然后 你应该将大文件分成小部分,然后尝试发送。并在服务器上加入这个小部分。

相关问题