发送文件和参数在Android API 23 HttpURLConnection服务器 [英] Send File And Parameters To Server With HttpURLConnection in android API 23

查看:251
本文介绍了发送文件和参数在Android API 23 HttpURLConnection服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 公共类PurchaseAsync extends AsyncTask< String,Void,Boolean> {

public static final String TAG = PurchaseAsync.class.getSimpleName();
public PurchaseAsync(ArrayList< CustomItem> parameters,String imageAddress,PurchaseListener listener){
this.parameters = parameters;
this.imageAddress = imageAddress;
this.listener = listener;
if(this.parameters == null){
this.parameters = new ArrayList<>();

LTH.dLog(WMH.WEBSERVICE,TAG + - >图片路径:+ imageAddress);
}
private String imageAddress =;
// ==========使用HashMap,它的作用类似于NameValuePair
ArrayList< CustomItem> parameters = new ArrayList<>();
私人PurchaseListener侦听器;
public interface PurchaseListener {
void execute(int exception,Boolean success,FactorItem msg);
}
private int customException = WMH.NO_EXCEPTION;
private FactorItem msg = new FactorItem();
@Override
protected void onPreExecute(){
progressDialog = ProgressDialog.show(App.getActivity(),
,App.getContext()。getString(R.string .pb_msg_purchase_request),true,false);
progressDialog.setCanceledOnTouchOutside(false);
super.onPreExecute();
}
私人ProgressDialog progressDialog;
@Override
保护无效onPostExecute(布尔成功){
super.onPostExecute(成功);
if(progressDialog!= null){
progressDialog.dismiss();
}
LTH.dLog(WMH.WEBSERVICE,TAG + - > customException:+ customException +,成功:+ success);
if(listener!= null){
listener.execute(customException,success,msg);


$ b $覆盖
保护布尔值doInBackground(String ... strings){
customException = WMH.NO_EXCEPTION;
尝试{
String strResult = readData(strings [0]);
if(strResult.equals()){
customException = customException == WMH.NO_EXCEPTION? WMH.INVALID_EXCEPTION:customException;
返回false;
} else {
JSONObject jsonObject = jsonParser(strResult);
if(jsonObject == null){
customException = customException == WMH.NO_EXCEPTION? WMH.INVALID_EXCEPTION:customException;
返回false;
}
pareFactor(jsonObject);
if(jsonObject.has(status)){
return jsonObject.getBoolean(status);
} else {
customException = customException == WMH.NO_EXCEPTION? WMH.INVALID_EXCEPTION:customException;
返回false;
} // end of else / if
}
} catch(Exception e){
customException = customException == WMH.NO_EXCEPTION? WMH.INVALID_EXCEPTION:customException;
LTH.eLog(WMH.JSON,TAG + - >异常错误在Json中:+ e.getMessage(),e);
}
返回false; (iJsonObject.has(result)){
if(iJsonObject.get(result)=
private void pareFactor(JSONObject iJsonObject)throws Exception { = null){
return; $!
$ b if(!(iJsonObject.get(result)instanceof JSONObject)){
return;

JSONObject jsonObject = iJsonObject.getJSONObject(result);
if(jsonObject.has(code)){
String code = jsonObject.getString(code);
msg.setCode(code);
int fid;
try {
fid = Integer.parseInt(jsonObject.getString(fid));
} catch(NumberFormatException nfe){
fid = 0;
//抛出新的异常(因子ID未分配正确);
}
msg.setItemId(fid);
if(jsonObject.has(price_number)){
String price_number = jsonObject.getString(price_number);
msg.setPayment(price_number);
msg.setTotal(price_number);

if(jsonObject.has(price)){
int price;
try {
price = Integer.parseInt(jsonObject.getString(price));
} catch(NumberFormatException nfe){
price = 0;
//抛出新的异常(因子ID未分配正确);
}
msg.setPaymentPrice(price);
msg.setTotalPrice(price);
}
}
} else {
抛出新的异常(因素信息未分配);


private JSONObject jsonParser(String strData)throws Exception {
if(!strData.equals()){
JSONObject jsonObject = new JSONObject strData是);
return jsonObject.getJSONObject(posts);
}
返回null;

private String readData(String strUrl){
LTH.dLog(WMH.WEBSERVICE,TAG + - > readData,Address:+ strUrl);
// ==========服务器通信部分 - 它比较长,但使用标准方法
// ==========编码字符串 - 我们必须用我们自定义的方法编码字符串(很简单)
String outPut =;
String attachmentName =image;
String attachmentFileName =;
String crlf =\r\\\
;
String twoHyphens = - ;
String boundary =*****;
int bytesRead = 0,bytesAvailable,bufferSize;
int maxBufferSize = WMH.MAX_BUFFER_SIZE;
/*if(imageAddress.contains(/)){
attachmentFileName = imageAddress.substring(imageAddress.lastIndexOf(/)+ 1,imageAddress.length());
} * /
attachmentFileName = imageAddress;
LTH.dLog(WMH.WEBSERVICE,TAG + - >附件名称:+ attachmentName);
尝试{
HttpURLConnection httpUrlConnection = null;
URL url =新的URL(strUrl);
httpUrlConnection =(HttpURLConnection)url.openConnection();
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setDoInput(true);
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setRequestMethod(POST);
// httpUrlConnection.setRequestProperty(User-Agent,Mozilla / 5.0(Macintosh; Intel Mac OS X 10_10_3)AppleWebKit / 537.36(KHTML,像Gecko)Chrome / 44.0.2403.155 Safari / 537.36);
httpUrlConnection.setRequestProperty(Connection,Keep-Alive);
httpUrlConnection.setRequestProperty(Cache-Control,no-cache);
httpUrlConnection.setRequestProperty(ENCTYPE,multipart / form-data);
httpUrlConnection.setRequestProperty(Content-Type,multipart / form-data; boundary =+ boundary);
if(imageAddress.length()> 4){
httpUrlConnection.setRequestProperty(attachmentName,attachmentFileName);

DataOutputStream request = new DataOutputStream(httpUrlConnection.getOutputStream());
request.writeBytes(twoHyphens + boundary + crlf); (imageAddress.length()> 4){
request.writeBytes(Content-Disposition:form-data; name = \+ attachmentName +\; filename = \\+ attachmentFileName +\+ crlf);
request.writeBytes(Content-Type:image / *+ crlf);
request.writeBytes(crlf);

/*BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
位图位图= BitmapFactory.decodeFile(imageAddress,options);
byte [] pixels = new byte [bitmap.getWidth()* bitmap.getHeight()];
for(int i = 0; i< bitmap.getWidth(); ++ i){
for(int j = 0; j< bitmap.getHeight(); ++ j){
//我们只对第一个字节的MSB感兴趣,因为其他3个字节对于B& W图像是相同的
像素[i + j] =(字节)((bitmap.getPixel (i,j)& 0x80)>> 7);

$ b request.write(pixels); * /

//代码...
FileInputStream fileInputStream = new FileInputStream(attachmentFileName);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
byte [] buffer = new byte [bufferSize];

//读取文件并将其写入表单...
bytesRead = fileInputStream.read(buffer,0,bufferSize);

while(bytesRead> 0){

request.write(buffer,0,bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
}
//代码。

request.writeBytes(crlf);
request.writeBytes(twoHyphens + boundary + crlf);
}

//添加到发送参数
for(int i = 0; i< parameters.size(); i ++){
String key = parameters。得到(I).getTitle();
String value =;

try {
value = URLEncoder.encode(parameters.get(i).getContent(),UTF-8);
} catch(UnsupportedEncodingException e){
LTH.eLog(TAG,e.getMessage(),e);
value = parameters.get(i).getContent();


LTH.dLog(WMH.WEBSERVICE,TAG + - >+ key +:+ value);
request.writeBytes(Content-Disposition:form-data; name = \+ key +\+ crlf);
request.writeBytes(crlf);
request.writeBytes(value);
request.writeBytes(crlf);
request.writeBytes(twoHyphens + boundary + crlf);
}

// request.writeBytes(twoHyphens + boundary + twoHyphens + crlf);

request.flush();
request.close();

int responseCode = httpUrlConnection.getResponseCode();
LTH.dLog(WMH.WEBSERVICE,TAG + - >响应代码:+ responseCode +,响应消息:+ httpUrlConnection.getResponseMessage());
if(responseCode == HttpsURLConnection.HTTP_OK){
InputStream responseStream = new BufferedInputStream(httpUrlConnection.getInputStream());

BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream,Charset.forName(UTF-8)));

String line =; ((line = responseStreamReader.readLine())!= null){
outPut + = line;
while
}
responseStreamReader.close();
}

httpUrlConnection.disconnect();
} catch(Exception exception){
LTH.dLog(WMH.WEBSERVICE,TAG + - >错误字符串输出结果:+ exception.getMessage(),exception);
return exception.toString();
}
LTH.dLog(WMH.WEBSERVICE,TAG + - >字符串输出结果:+ outPut);
返回outPut;


code

$ b $ p

  $ item = new stdclass(); 
$ item-> image = $ _FILES ['image'];

$ imageFileType = pathinfo($ _ FILES ['image'],PATHINFO_EXTENSION);
$ check = getimagesize($ _ FILES ['image'] [tmp_name]);
if($ check!== false){
$ item-> file_status =文件是图像 - 。 $ check [mime]。 ;
} else {
$ item-> file_status =文件不是图片。
}

$ item-> imageFileType = $ imageFileType;
$ item-> file_check = $ check;

$ results_array ['msg'] ='测试';
$ results_array ['status'] = false;
$ results_array ['result'] = $ item;
$ b $ echo $ ws-> unicodeString(json_encode(array('posts'=>($ results_array))),'UTF-8');

参数成功接收文件,但请记住 attachmentFileName if 完整文件路径

解决方案

Android中的多部分请求。我已经清楚地解释了多部分请求的结构,每个单一的文本在身体意味着什么,如何构建一个自己在Android(与代码),以及它是如何类似与自动生成的,当你打像firefox这样的浏览器提供服务,最后如何在JSP和Java rest API中使用webrequest。有一目了然:)
多部分请求复杂?再次考虑一下。

编辑

首先要说的是:)顾名思义,多部分表单数据是只有一个包含多个部分的请求:)
例子:这里是一个由firefox生成的multipart请求:)

  ------ WebKitFormBoundaryQHJL2hsKnlU26Mm3 
Content-Disposition:form-data; NAME = profilePic;文件名=66.jpg
内容类型:application / octet-stream

//你的图片数据出现在这里
------ WebKitFormBoundaryQHJL2hsKnlU26Mm3
内容处理:表单数据; name =testingName

Myfile.jpg //发送文件名作为参数,你可以传递你想要的参数:)
------ WebKitFormBoundaryQHJL2hsKnlU26Mm3--

你能看到吗?有两个部分,一个包含一个jpg文件,另一个包含一个字符串(表单数据):)

在你的情况下,一个部分将包含图像,其他人将包含其余的参数。所以为了通知服务器哪个部分包含你将不得不以合适的格式创建请求:)在你的情况下,第一部分让我们假设图像。

  DataOutputStream dos = new DataOutputStream(con.getOutputStream()); 
dos.writeBytes(twoHyphens + boundary + lineEnd);

dos.writeBytes(Content-Disposition:form-data; name = \image\; filename = \+ imageAddress +\+ lineEnd);

dos.writeBytes(Content-Type:image / jpeg+ lineEnd);
dos.writeBytes(lineEnd);
dos.write(byteArray); //你的图像数组buddy
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes(Content-Disposition:form-data; name = \您的参数名称\+ crlf);
dos.writeBytes(lineEnd);
dos.writeBytes(testName); //你的参数值
dos.writeBytes(lineEnd); //添加多个参数write Content-Disposition:form-data; name = \您的参数名称\+ crlf再次不断重复,直到这里:)
dos.writeBytes(twoHyphens + boundary + twoHyphens);
dos.flush();
dos.close();

你是否看到你错过了它的内容类型:)在指定内容类型之后,你需要输入一个行结束符(你能看到firefox生成的多部分表单请求)

在指定图像内容之后,你需要启动第二部分再次输入新行:)
然后用twoHyphens + boundary + crlf
指定新节的开始处用content-Disposition指定内容类型:form-data; name = \your参数名称

输入新行添加参数并再次输入新行,并再次用新行关闭该行。重复它,直到你添加所有的参数(严重的是我更喜欢创建所有参数的JSON,并把它作为一个部分发送),然后关闭多连接请求与两个连字符+边界+ twoHyphens

多数民众赞成在:)你现在得到你的错误? :)
$ b 总结:您将不得不创建一个multipart-form数据请求,以便与firefox浏览器发布的multipart-form数据的结构完全匹配:)

所以,如果你看到我发布的任何代码,除了按照模板添加文本和按照模板添加文本外,没有其他更多的事情:)相信我的服务器站在它,因为浏览器不会犯错误,你知道:)

仍然有疑问问我:)在这里帮助。而我上面粘贴的代码不仅仅是一个逻辑的实际代码:)

After many tries I Solved it, there is the code i use to send parameters and image :

    public class PurchaseAsync extends AsyncTask<String, Void, Boolean> {

    public static final String TAG = PurchaseAsync.class.getSimpleName();
    public PurchaseAsync(ArrayList<CustomItem> parameters, String imageAddress, PurchaseListener listener){
        this.parameters = parameters;
        this.imageAddress = imageAddress;
        this.listener = listener;
        if(this.parameters == null){
            this.parameters = new ArrayList<>();
        }
        LTH.dLog(WMH.WEBSERVICE, TAG + " -> Image path : " + imageAddress);
    }
    private String imageAddress = "";
    // ========== Use HashMap, it works similar to NameValuePair
    ArrayList<CustomItem> parameters = new ArrayList<>();
    private PurchaseListener listener;
    public interface PurchaseListener {
        void execute(int exception, Boolean success, FactorItem msg);
    }
    private int customException = WMH.NO_EXCEPTION;
    private FactorItem msg = new FactorItem();
    @Override
    protected void onPreExecute() {
        progressDialog = ProgressDialog.show(App.getActivity(),
                "", App.getContext().getString(R.string.pb_msg_purchase_request), true, false);
        progressDialog.setCanceledOnTouchOutside(false);
        super.onPreExecute();
    }
    private ProgressDialog progressDialog;
    @Override
    protected void onPostExecute(Boolean success) {
        super.onPostExecute(success);
        if(progressDialog != null){
            progressDialog.dismiss();
        }
        LTH.dLog(WMH.WEBSERVICE, TAG + " -> customException : " + customException + " , Success : " + success);
        if(listener != null){
            listener.execute(customException, success, msg);
        }
    }

    @Override
    protected Boolean doInBackground(String... strings) {
        customException = WMH.NO_EXCEPTION;
        try{
            String strResult = readData(strings[0]);
            if(strResult.equals("")){
                customException = customException == WMH.NO_EXCEPTION ? WMH.INVALID_EXCEPTION : customException;
                return false;
            }else{
                JSONObject jsonObject = jsonParser(strResult);
                if(jsonObject == null){
                    customException = customException == WMH.NO_EXCEPTION ? WMH.INVALID_EXCEPTION : customException;
                    return false;
                }
                pareFactor(jsonObject);
                if (jsonObject.has("status")) {
                    return jsonObject.getBoolean("status");
                } else {
                    customException = customException == WMH.NO_EXCEPTION ? WMH.INVALID_EXCEPTION : customException;
                    return false;
                } // end of else/if
            }
        }catch (Exception e){
            customException = customException == WMH.NO_EXCEPTION ? WMH.INVALID_EXCEPTION : customException;
            LTH.eLog(WMH.JSON, TAG + " -> Exception Error In Json: " + e.getMessage(), e);
        }
        return false;
    }
    private void pareFactor(JSONObject iJsonObject) throws Exception{
        if (iJsonObject.has("result")) {
            if(iJsonObject.get("result") == null){
                return;
            }
            if(!(iJsonObject.get("result") instanceof JSONObject)){
                return;
            }
            JSONObject jsonObject = iJsonObject.getJSONObject("result");
            if(jsonObject.has("code")){
                String code = jsonObject.getString("code");
                msg.setCode(code);
                int fid;
                try {
                    fid = Integer.parseInt(jsonObject.getString("fid"));
                }catch (NumberFormatException nfe){
                    fid = 0;
                    // throw new Exception("Factor ID Not Assigned Correctly");
                }
                msg.setItemId(fid);
                if(jsonObject.has("price_number")) {
                    String price_number = jsonObject.getString("price_number");
                    msg.setPayment(price_number);
                    msg.setTotal(price_number);
                }
                if(jsonObject.has("price")) {
                    int price;
                    try {
                        price = Integer.parseInt(jsonObject.getString("price"));
                    }catch (NumberFormatException nfe){
                        price = 0;
                        // throw new Exception("Factor ID Not Assigned Correctly");
                    }
                    msg.setPaymentPrice(price);
                    msg.setTotalPrice(price);
                }
            }
        } else {
            throw new Exception("Factor Information Not Assigned");
        }
    }
    private JSONObject jsonParser(String strData) throws Exception{
        if(!strData.equals("")){
            JSONObject jsonObject = new JSONObject(strData);
            return jsonObject.getJSONObject("posts");
        }
        return null;
    }
    private String readData(String strUrl){
        LTH.dLog(WMH.WEBSERVICE, TAG + " -> readData, Address : " + strUrl);
        // ========== Server Communication part - it's relatively long but uses standard methods
        // ========== Encoded String - we will have to encode string by our custom method (Very easy)
        String outPut = "";
        String attachmentName = "image";
        String attachmentFileName = "";
        String crlf = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead = 0, bytesAvailable, bufferSize;
        int maxBufferSize = WMH.MAX_BUFFER_SIZE;
        /*if(imageAddress.contains("/")){
            attachmentFileName = imageAddress.substring(imageAddress.lastIndexOf("/")+1, imageAddress.length());
        }*/
        attachmentFileName = imageAddress;
        LTH.dLog(WMH.WEBSERVICE, TAG + " -> Attachment Name : " + attachmentName);
        try{
            HttpURLConnection httpUrlConnection = null;
            URL url = new URL(strUrl);
            httpUrlConnection = (HttpURLConnection) url.openConnection();
            httpUrlConnection.setUseCaches(false);
            httpUrlConnection.setDoInput(true);
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setRequestMethod("POST");
            // httpUrlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36");
            httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");
            httpUrlConnection.setRequestProperty("Cache-Control", "no-cache");
            httpUrlConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
            httpUrlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            if(imageAddress.length() > 4) {
                httpUrlConnection.setRequestProperty(attachmentName, attachmentFileName);
            }
            DataOutputStream request = new DataOutputStream(httpUrlConnection.getOutputStream());
            request.writeBytes(twoHyphens + boundary + crlf);
            if(imageAddress.length() > 4) {
                request.writeBytes("Content-Disposition: form-data; name=\"" + attachmentName + "\";filename=\"" + attachmentFileName + "\"" + crlf);
                request.writeBytes("Content-Type: image/*" + crlf);
                request.writeBytes(crlf);

                /*BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                Bitmap bitmap = BitmapFactory.decodeFile(imageAddress, options);
                byte[] pixels = new byte[bitmap.getWidth() * bitmap.getHeight()];
                for (int i = 0; i < bitmap.getWidth(); ++i) {
                    for (int j = 0; j < bitmap.getHeight(); ++j) {
                        //we're interested only in the MSB of the first byte, since the other 3 bytes are identical for B&W images
                        pixels[i + j] = (byte) ((bitmap.getPixel(i, j) & 0x80) >> 7);
                    }
                }
                request.write(pixels);*/

                // Code ...
                FileInputStream fileInputStream = new FileInputStream(attachmentFileName);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                byte[] buffer = new byte[bufferSize];

                // read file and write it into form...
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0) {

                    request.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                }
                // Code .

                request.writeBytes(crlf);
                request.writeBytes(twoHyphens + boundary + crlf);
            }

            // Added To Send Parameters
            for(int i=0; i<parameters.size();i++){
                String key = parameters.get(i).getTitle();
                String value = "";

                try {
                    value = URLEncoder.encode(parameters.get(i).getContent(), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    LTH.eLog(TAG, e.getMessage(), e);
                    value = parameters.get(i).getContent();
                }

                LTH.dLog(WMH.WEBSERVICE, TAG + " -> " + key + " : " + value);
                request.writeBytes("Content-Disposition: form-data; name=\""+key+"\"" + crlf);
                request.writeBytes(crlf);
                request.writeBytes(value);
                request.writeBytes(crlf);
                request.writeBytes(twoHyphens + boundary + crlf);
            }

            // request.writeBytes(twoHyphens + boundary + twoHyphens + crlf);

            request.flush();
            request.close();

            int responseCode = httpUrlConnection.getResponseCode();
            LTH.dLog(WMH.WEBSERVICE, TAG + " -> Response Code : " + responseCode + " , Response Message : " + httpUrlConnection.getResponseMessage());
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                InputStream responseStream = new BufferedInputStream(httpUrlConnection.getInputStream());

                BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream, Charset.forName("UTF-8")));

                String line = "";
                while ((line = responseStreamReader.readLine()) != null) {
                    outPut+=line;
                }
                responseStreamReader.close();
            }

            httpUrlConnection.disconnect();
        } catch (Exception exception){
            LTH.dLog(WMH.WEBSERVICE, TAG + " -> Error String OUTPUT Result : " + exception.getMessage(), exception);
            return exception.toString();
        }
        LTH.dLog(WMH.WEBSERVICE, TAG + " -> String OUTPUT Result : " + outPut);
        return outPut;
    }
}

php :

    $item = new stdclass();
    $item->image = $_FILES['image'];

    $imageFileType = pathinfo($_FILES['image'],PATHINFO_EXTENSION);
    $check = getimagesize($_FILES['image']["tmp_name"]);
    if($check !== false) {
        $item->file_status = "File is an image - " . $check["mime"] . ".";
    } else {
        $item->file_status = "File is not an image.";
    }

$item->imageFileType = $imageFileType;
$item->file_check = $check;

$results_array['msg'] = 'Test';
$results_array['status'] = false;
$results_array['result'] = $item;

echo $ws->unicodeString(json_encode(array('posts'=>($results_array))), 'UTF-8');

Parameter receive successfully with file, But Remember attachmentFileName if full file path .

I have written a blog on Multipart request in Android. I have clearly explained the structure of the multipart request, what every single text in the body means, how to construct one on your own in android (with code) and also how it resembles with the one that gets generated automatically when you hit the post service from browsers like firefox and finally how to consume the webrequest in JSP and java rest API. Have a glance :) Is Multipart request complicated? Think again.

EDIT

First thing first :) As name suggests multipart form data is nothing but a single request containing multiple parts in it :) Example: here is a multipart request generated by firefox :)

------WebKitFormBoundaryQHJL2hsKnlU26Mm3
Content-Disposition: form-data; name="profilePic"; filename="66.jpg"
Content-Type: application/octet-stream

//your image data appears here
------WebKitFormBoundaryQHJL2hsKnlU26Mm3
Content-Disposition: form-data; name="testingName"

Myfile.jpg //file name sent as parameter you can pass whatever parameter you want :)
------WebKitFormBoundaryQHJL2hsKnlU26Mm3--

Can you see that??? There are two parts one contains a jpg file and other contains a string (form data) :)

In your case one part will contain the image and others will contain the rest of the parameters. So in order to inform the server which part contains what you will have to create request in proper format :) In your case first part lets assume image so.

DataOutputStream dos = new DataOutputStream(con.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);

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

dos.writeBytes("Content-Type: image/jpeg" + lineEnd);
dos.writeBytes(lineEnd);
dos.write(byteArray);//your image array here buddy
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"your parameter name\"" + crlf);
dos.writeBytes(lineEnd);
dos.writeBytes(testName);//your parameter value
dos.writeBytes(lineEnd); //to add multiple parameters write Content-Disposition: form-data; name=\"your parameter name\"" + crlf again and keep repeating till here :)
dos.writeBytes(twoHyphens + boundary + twoHyphens);
dos.flush();
dos.close();

Did you see what you were missing yes its content-type :) afterspecifying content-type you will need to enter a line end (can you see the firefox generated multipart form request)

After specifying image content you need to start the second section so enter the new line again :) Then specify the beginning of new section with twoHyphens + boundary + crlf Specify the content type again :) with Content-Disposition: form-data; name=\"your parameter name\

Enter the new line add the parameter and enter the new line again and close the section with new line again.

Repeat it untill you add all your parameter (seriously I prefer creating json of all parameter and sending it as one section) and then close multipart request with twoHyphens + boundary + twoHyphens

Thats it :) Did you get your error now?? :)

Summary : You will have to create a multipart-formdata request in such a way that it exactly matches the structure of the multipart-formdata I posted from fire fox browser :)

So if you see whatever the code I posted am doing nothing more than following the template and adding texts as per the template :) believe me server under stands it because browsers wont make mistakes you know :)

Still have a doubt ask me :) am here to help. And the code above I pasted isn't just a logical one its actually from the working code :)

这篇关于发送文件和参数在Android API 23 HttpURLConnection服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆