本文介绍了的multipart / form-data的ENCTYPE JSON为Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要上传图像和信息。我想使用的的multipart /表单 JSON数据为Android。我也看到这个堆栈溢出问题Android:How为MP3档案,并上传图片到http服务器?
但它并没有为我工作。
这是我的code:
保护无效doFileUpload(){
意向I = getIntent();
字符串路径= i.getStringExtra(pathimage);
HttpURLConnection的康恩= NULL;
DataOutputStream类DOS = NULL;
DataInputStream以inStream中= NULL;
字符串existingFileName =路径;
字符串lineEnd =\\ r \\ n;
串twoHyphens = - ;
字符串边界=*****;
INT读取动作,方bytesAvailable,缓冲区大小;
字节[]缓冲区;
INT MAXBUFFERSIZE = 1 * 1024 * 1024;
串responseFromServer =;
字符串urlString = Constants.url_create_store;
尝试
{
// ------------------客户端请求
的FileInputStream的FileInputStream =新的FileInputStream(新文件(existingFileName));
//打开一个URL连接到这个Servlet
网址URL =新的URL(urlString);
//打开HTTP连接的URL
康恩=(HttpURLConnection类)url.openConnection();
//允许输入
conn.setDoInput(真);
//允许输出
conn.setDoOutput(真);
//不要使用缓存副本。
conn.setUseCaches(假);
//使用POST方法。
conn.setRequestMethod(POST);
conn.setRequestProperty(连接,保持活动);
conn.setRequestProperty(内容类型,的multipart / form-data的;边界=+边界);
DOS =新的DataOutputStream类(conn.getOutputStream());
dos.writeBytes(twoHyphens +边界+ lineEnd);
dos.writeBytes(内容处置:表格数据;名称= \\UploadedFile的\\;文件名= \\+ existingFileName +\\+ lineEnd);
dos.writeBytes(lineEnd);
//创建最大大小的缓冲区
参考bytesAvailable = fileInputStream.available();
BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);
缓冲区=新的字节[缓冲区大小]
//读取文件,并将其写入形式...
读取动作= fileInputStream.read(缓冲液,0,缓冲区大小);
而(读取动作大于0)
{
dos.write(缓冲液,0,缓冲区大小);
参考bytesAvailable = fileInputStream.available();
BUFFERSIZE = Math.min(方bytesAvailable,MAXBUFFERSIZE);
读取动作= fileInputStream.read(缓冲液,0,缓冲区大小);
}
//发送文件数据后necesssary多部分的表单数据...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens +边界+ twoHyphens + lineEnd);
//关闭流
Log.e(调试,文件写入);
fileInputStream.close();
dos.flush();
dos.close();
}
赶上(MalformedURLException的前)
{
Log.e(调试,错误:+ ex.getMessage(),除息);
}
赶上(IOException异常IOE)
{
Log.e(调试,错误:+ ioe.getMessage(),IOE);
}
// ------------------读取服务器响应
尝试{
inStream中=新DataInputStream所(conn.getInputStream());
字符串str; 而((海峡= inStream.readLine())!= NULL)
{
Log.e(调试,服务器响应+ STR);
}
inStream.close();
}
赶上(IOException异常ioex){
Log.e(调试,错误:+ ioex.getMessage(),ioex);
}
} }
这是我的logcat:
11月10日至3日:17:07.782:DEBUG / dalvikvm(119):GC_EXTERNAL_ALLOC释放在839ms 706对象/ 34184字节
11月10日至3日:17:13.052:信息/ ActivityManager(67):启动活动:意向{CMP = shoop3.android.edu / .Activity3(有临时演员)}
11月10日至3日:17:13.732:DEBUG / dalvikvm(468):GC_EXTERNAL_ALLOC释放1652对象/在187ms 91728字节
11月10日至3日:17:15.162:信息/ ActivityManager(67):显示活动shoop3.android.edu/.Activity3:1929年毫秒(总1929年毫秒)
11月10日至3日:17:20.942:ERROR /调试(468):文件被写入
11月10日至3日:17:24.802:ERROR /调试(468):服务器响应{地位:1}
11月10日至3日:17:25.272:ERROR / JSON解析器(468):错误分析数据org.json.JSONException:在字符输入0结束
11月10日至3日:17:25.282:DEBUG /创建响应(468):{身份:1}
11月10日至3日:17:25.312:信息/ ActivityManager(67):启动活动:意向{CMP = shoop3.android.edu / .shoop3Activity}
11月10日至3日:17:26.825:信息/ ActivityManager(67):显示活动shoop3.android.edu/.shoop3Activity:1349毫秒(共1349毫秒)
11月10日至3日:19:24.372:DEBUG / SntpClient(67):请求时失败:java.net.SocketException异常:地址协议不支持
解决方案
您可以使用此SimpleMultipartEntity类用于发送多部分数据:
公共类SimpleMultipartEntity实现HttpEntity {私人最终静态的char [] MULTIPART_CHARS =-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
.toCharArray();私人字符串边界= NULL;
ByteArrayOutputStream出=新ByteArrayOutputStream();
布尔isSetLast = FALSE;
布尔isSetFirst = FALSE;公共SimpleMultipartEntity(){
最终StringBuffer的BUF =新的StringBuffer();
最后随机兰特=新的随机();
对(INT I = 0; I&小于30;我++){
buf.append(MULTIPART_CHARS [rand.nextInt(MULTIPART_CHARS.length)]);
}
this.boundary = buf.toString();}公共无效writeFirstBoundaryIfNeeds(){
如果(!isSetFirst){
尝试{
out.write(( - +边界+\\ r \\ n)的getBytes());
}赶上(最终IOException异常五){
e.printStackTrace();
}
}
isSetFirst =真;
}公共无效writeLastBoundaryIfNeeds(){
如果(isSetLast){
返回;
}
尝试{
out.write((\\ r \\ N--+边界+ - \\ r \\ n)的getBytes());
}赶上(最终IOException异常五){
e.printStackTrace();
}
isSetLast =真;
}公共无效addPart(最后字符串的关键,最终的字符串值){
writeFirstBoundaryIfNeeds();
尝试{
out.write((内容处置:表格数据;名称= \\+键+\\\\ r \\ n)
.getBytes());
out.write(内容类型:text / plain的;字符集= UTF-8 \\ r \\ n.getBytes());
out.write(内容传输编码:8位\\ r \\ n \\ r \\ n.getBytes());
out.write(value.getBytes());
out.write((\\ r \\ N--+边界+\\ r \\ n)的getBytes());
}赶上(最终IOException异常五){
e.printStackTrace();
}
}公共无效addPart(最终字符串键,最后字符串的文件名,
最终的InputStream FIN){
addPart(键,文件名,翅,应用程序/八位字节流);
}公共无效addPart(最终字符串键,最后字符串的文件名,
最终的InputStream翅,串式){
writeFirstBoundaryIfNeeds();
尝试{
键入=内容类型:+类型+\\ r \\ n;
out.write((内容处置:表格数据;名称= \\+键
+\\; 。文件名= \\+文件名+\\\\ r \\ n)的getBytes());
out.write(type.getBytes());
out.write(内容传输编码:二进制\\ r \\ n \\ r \\ n.getBytes()); 最后一个字节[] TMP =新的字节[4096];
int类型l = 0;
而((1- = fin.read(TMP))!= - 1){
out.write(TMP,0,1);
}
了out.flush();
}赶上(最终IOException异常五){
e.printStackTrace();
} {最后
尝试{
fin.close();
}赶上(最终IOException异常五){
e.printStackTrace();
}
}
}公共无效addPart(最终字符串键,最后的文件值){
尝试{
addPart(键,value.getName(),新的FileInputStream(值));
}赶上(最终FileNotFoundException异常五){
e.printStackTrace();
}
}公共字符串getBoundary(){
返回边界;
}公共无效setBoundary(字符串边界){
this.boundary =边界;
}@覆盖
众长getContentLength(){
writeLastBoundaryIfNeeds();
返回out.toByteArray()的长度。
}@覆盖
公共头的getContentType(){
返回新BasicHeader(内容类型,的multipart / form-data的;边界=
+边界);
}@覆盖
公共布尔isChunked(){
返回false;
}@覆盖
公共布尔isRepeatable(){
返回false;
}@覆盖
公共布尔则将isStreaming(){
返回false;
}@覆盖
公共无效的writeTo(OutputStream中最终outstream)抛出IOException
outstream.write(out.toByteArray());
}@覆盖
公共头getContentEncoding(){
返回null;
}@覆盖
公共无效consumeContent()抛出IOException异常,
UnsupportedOperationException异常{
如果(则将isStreaming()){
抛出新UnsupportedOperationException异常(
流实体没有实现#consumeContent());
}
}@覆盖
公众的InputStream的getContent()抛出IOException异常,
UnsupportedOperationException异常{
返回ByteArrayInputStream的新(out.toByteArray());
}}
用法:
字符串serviceUri =服务URL;
InputStream中的FileInputStream = mInputStream; //你的文件流
字符串文件名=你的文件名;
字符串的FileKey =键名什么样的服务器正在寻找
HashMap的<字符串,字符串> headerparts = mHeaderParts; //你需要一起发送其他头部分。 HttpClient的HttpClient的=新DefaultHttpClient();
HttpPost httpPost =新HttpPost(serviceUri);
SimpleMultipartEntity实体=新SimpleMultipartEntity();
httpPost.setHeader(接受,应用/ JSON);
httpPost.setHeader(内容类型,的multipart / form-data的;边界=
+ entity.getBoundary());
entity.writeFirstBoundaryIfNeeds(); 如果(headerparts!= NULL){
对象[] =的keySet headerparts.keySet()的toArray()。
的for(int i = 0; I< keySet.length;我++){
字符串键的keySet = [I]的ToString();
字符串值= headerparts.get(键);
entity.addPart(键,值);
}
} entity.addPart(FileKey加密,文件名的FileInputStream);
entity.writeLastBoundaryIfNeeds();
httpPost.setEntity(实体); 尝试{
mResponse = httpClient.execute(httpPost);
}赶上(例外五){
e.printStackTrace();
}
I want to upload image and its information. I wanna to use multipart/ form data json for android. I have also seen this Stack Overflow question Android:How to upload .mp3 file and image to http server?
but it didn't worked for me.
This is my code:
protected void doFileUpload(){
Intent i = getIntent();
String path = i.getStringExtra("pathimage");
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = path;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = Constants.url_create_store;
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// close streams
Log.e("Debug","File is written");
fileInputStream.close();
dos.flush();
dos.close();
}
catch (MalformedURLException ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
catch (IOException ioe)
{
Log.e("Debug", "error: " + ioe.getMessage(), ioe);
}
//------------------ read the SERVER RESPONSE
try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;
while (( str = inStream.readLine()) != null)
{
Log.e("Debug","Server Response "+str);
}
inStream.close();
}
catch (IOException ioex){
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
}
}
and this is my logcat:
10-03 11:17:07.782: DEBUG/dalvikvm(119): GC_EXTERNAL_ALLOC freed 706 objects / 34184 bytes in 839ms
10-03 11:17:13.052: INFO/ActivityManager(67): Starting activity: Intent { cmp=shoop3.android.edu/.Activity3 (has extras) }
10-03 11:17:13.732: DEBUG/dalvikvm(468): GC_EXTERNAL_ALLOC freed 1652 objects / 91728 bytes in 187ms
10-03 11:17:15.162: INFO/ActivityManager(67): Displayed activity shoop3.android.edu/.Activity3: 1929 ms (total 1929 ms)
10-03 11:17:20.942: ERROR/Debug(468): File is written
10-03 11:17:24.802: ERROR/Debug(468): Server Response {"status":1}
10-03 11:17:25.272: ERROR/JSON Parser(468): Error parsing data org.json.JSONException: End of input at character 0 of
10-03 11:17:25.282: DEBUG/Create Response(468): {"status":1}
10-03 11:17:25.312: INFO/ActivityManager(67): Starting activity: Intent { cmp=shoop3.android.edu/.shoop3Activity }
10-03 11:17:26.825: INFO/ActivityManager(67): Displayed activity shoop3.android.edu/.shoop3Activity: 1349 ms (total 1349 ms)
10-03 11:19:24.372: DEBUG/SntpClient(67): request time failed: java.net.SocketException: Address family not supported by protocol
解决方案
You can use this SimpleMultipartEntity class for sending Multipart data :
public class SimpleMultipartEntity implements HttpEntity {
private final static char[] MULTIPART_CHARS = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
.toCharArray();
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public SimpleMultipartEntity() {
final StringBuffer buf = new StringBuffer();
final Random rand = new Random();
for (int i = 0; i < 30; i++) {
buf.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
}
this.boundary = buf.toString();
}
public void writeFirstBoundaryIfNeeds() {
if (!isSetFirst) {
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
e.printStackTrace();
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if (isSetLast) {
return;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
e.printStackTrace();
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n")
.getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
e.printStackTrace();
}
}
public void addPart(final String key, final String fileName,
final InputStream fin) {
addPart(key, fileName, fin, "application/octet-stream");
}
public void addPart(final String key, final String fileName,
final InputStream fin, String type) {
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: " + type + "\r\n";
out.write(("Content-Disposition: form-data; name=\"" + key
+ "\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
e.printStackTrace();
} finally {
try {
fin.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
}
public void addPart(final String key, final File value) {
try {
addPart(key, value.getName(), new FileInputStream(value));
} catch (final FileNotFoundException e) {
e.printStackTrace();
}
}
public String getBoundary() {
return boundary;
}
public void setBoundary(String boundary) {
this.boundary = boundary;
}
@Override
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary="
+ boundary);
}
@Override
public boolean isChunked() {
return false;
}
@Override
public boolean isRepeatable() {
return false;
}
@Override
public boolean isStreaming() {
return false;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
@Override
public Header getContentEncoding() {
return null;
}
@Override
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
@Override
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}
}
Usage :
String serviceUri = "service url";
InputStream fileInputStream = mInputStream; //Your file stream
String fileName = "your file name";
String fileKey = "Key name what server is looking for"
HashMap<String, String> headerparts = mHeaderParts; //Other header parts that you need to send along.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(serviceUri);
SimpleMultipartEntity entity = new SimpleMultipartEntity();
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "multipart/form-data; boundary="
+ entity.getBoundary());
entity.writeFirstBoundaryIfNeeds();
if (headerparts != null) {
Object[] keySet = headerparts.keySet().toArray();
for (int i = 0; i < keySet.length; i++) {
String key = keySet[i].toString();
String value = headerparts.get(key);
entity.addPart(key, value);
}
}
entity.addPart(fileKey, fileName, fileInputStream);
entity.writeLastBoundaryIfNeeds();
httpPost.setEntity(entity);
try {
mResponse = httpClient.execute(httpPost);
} catch (Exception e) {
e.printStackTrace();
}
这篇关于的multipart / form-data的ENCTYPE JSON为Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!