android httppost文件,Android httpPost with parameters and file

This works like charm for me:

public int uploadFile(String sourceFileUri) {

String fileName=sourceFileUri;

HttpURLConnection conn = null;

DataOutputStream dos = null;

String lineEnd = "\r\n";

String twoHyphens = "--";

String boundary = "------hellojosh";

int bytesRead, bytesAvailable, bufferSize;

byte[] buffer;

int maxBufferSize = 1 * 1024 * 1024;

File sourceFile = new File(fileName);

Log.e("joshtag", "Uploading: sourcefileURI, "+fileName);

if (!sourceFile.isFile()) {

Log.e("uploadFile", "Source File not exist :"+appSingleton.getInstance().photouri);//FullPath);

runOnUiThread(new Runnable() {

public void run() {

//messageText.setText("Source File not exist :"

}

});

return 0; //RETURN #1

}

else{

try{

FileInputStream fileInputStream = new FileInputStream(sourceFile);

URL url = new URL(upLoadServerUri);

Log.v("joshtag",url.toString());

// Open a HTTP connection to the URL

conn = (HttpURLConnection) url.openConnection();

conn.setDoInput(true); // Allow Inputs

conn.setDoOutput(true); // Allow Outputs

conn.setUseCaches(false); // Don't use a Cached Copy s

conn.setRequestMethod("POST");

conn.setRequestProperty("Connection", "Keep-Alive");

conn.setRequestProperty("ENCTYPE", "multipart/form-data");

conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

conn.setRequestProperty("file", fileName);

conn.setRequestProperty("user", user_id));

dos = new DataOutputStream(conn.getOutputStream());

//ADD Some -F Form parameters, helping method

//... is declared down below

addFormField(dos, "someParameter", "someValue");

dos.writeBytes(twoHyphens + boundary + lineEnd);

dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + fileName + "\"" + 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);

Log.i("joshtag","->");

}

// send multipart form data necesssary after file data...

dos.writeBytes(lineEnd);

dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// Responses from the server (code and message)

serverResponseCode = conn.getResponseCode();

String serverResponseMessage = conn.getResponseMessage().toString();

Log.i("joshtag", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

// ------------------ read the SERVER RESPONSE

DataInputStream inStream;

try {

inStream = new DataInputStream(conn.getInputStream());

String str;

while ((str = inStream.readLine()) != null) {

Log.e("joshtag", "SOF Server Response" + str);

}

inStream.close();

}

catch (IOException ioex) {

Log.e("joshtag", "SOF error: " + ioex.getMessage(), ioex);

}

//close the streams //

fileInputStream.close();

dos.flush();

dos.close();

if(serverResponseCode == 200){

//Do something

}//END IF Response code 200

dialog.dismiss();

}//END TRY - FILE READ

catch (MalformedURLException ex) {

ex.printStackTrace();

Log.e("joshtag", "UL error: " + ex.getMessage(), ex);

} //CATCH - URL Exception

catch (Exception e) {

e.printStackTrace();

Log.e("Upload file to server Exception", "Exception : "+ e.getMessage(), e);

} //

return serverResponseCode; //after try

}//END ELSE, if file exists.

}

public static String lineEnd = "\r\n";

public static String twoHyphens = "--";

public static String boundary = "------------------------afb19f4aeefb356c";

public static void addFormField(DataOutputStream dos, String parameter, String value){

try {

dos.writeBytes(twoHyphens + boundary + lineEnd);

dos.writeBytes("Content-Disposition: form-data; name=\""+parameter+"\"" + lineEnd);

dos.writeBytes(lineEnd);

dos.writeBytes(value);

dos.writeBytes(lineEnd);

}

catch(Exception e){

}

}

UPDATE: If you need to send parameters along with the file,

use:

conn.setRequestProperty("someParameter","someValue")

//or

addFormField(DataOutputStream dos, String parameter, String value)

...as shown in the code above. One or the other should work, if the server you are trying to connect to is not completely known to you.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值