1

多次嘗試我解決了這個問題之後,還有就是我用它來發送參數和圖像的代碼:發送文件和參數,服務器與HttpURLConnection的android系統API 23

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'); 

參數文件接收成功,但請記住attachmentFileName if full file path

+0

您正在獲取的響應代碼是什麼? – Exception

+0

檢查輸出甚至是其他響應代碼,以便您可以獲取有關該錯誤的更多詳細信息。 – Exception

+0

@Exception它是200,問題是傳遞參數與圖像文件到服務器 – AndroSco

回答

6

我在Android上編寫了一個關於Multipart請求的博客。我已經清楚地解釋了多部分請求的結構,身體中的每一個單詞都意味着什麼,如何在android中自己構造一個(帶有代碼),以及它如何與您在點擊帖子時自動生成的類似來自Firefox等瀏覽器的服務,以及如何使用JSP和Java rest API中的webrequest。有一目瞭然:) Is Multipart request complicated? Think again.

EDIT

第一件事第一:)正如名字所暗示的多部分形式的數據是什麼,但含有它的多個部分的單個請求:) 示例:這裏是由產生的多部分請求火狐:)

------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-- 

你能看到嗎?有兩個部分一個包含一個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);//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(); 

你看到你錯過了什麼是它的內容類型:) afterspecifying內容類型,您將需要輸入一個行結束(你可以看到Firefox的產生多形式要求)

指定後圖像內容,你需要開始第二部分,從而進入新的生產線再次:) 然後指定與twoHyphens +邊界+ CRLF 新節的開頭指定內容再次鍵入:)與內容處置:表格數據;名字= \「您的參數\

輸入新行添加參數並再次輸入新的生產線,並再次關閉與新線的部分。

重複它,直到你添加所有參數(嚴重,我更喜歡的名字創建所有參數的JSON和發送它作爲一個部分),並與twoHyphens +邊界+ twoHyphens然後關閉多要求

完蛋了:)你現在得到你的錯誤?:)

摘要:您將有創建一個多部分形式的數據請求,使其與多部分數據結構完全匹配, formdata我從火狐瀏覽器發佈:)

因此,如果你看到我發佈的任何代碼,除了遵循模板和根據模板添加文本之外,沒有其他更多的事情:)相信我的服務器,因爲瀏覽器不會犯錯誤你知道:)

還有一個疑惑地問我:)我在這裏幫助。並且上面我粘貼的代碼不僅僅是一個合乎邏輯的代碼:)

+0

它只發送圖像到服務器,我想發送參數和圖像 – AndroSco

+0

@AndroSco如果你已經看到了代碼正確,你會注意到,我創建了兩個部分在郵件正文中。消息體中的第一節有「Content-Type:image/jpeg」+ crlf和二進制圖像內容:)第二部分有一個名爲testName的參數:)因此,我發送兩件事情之一是圖像和一個字符串,它是這個人的名字 –

+0

我想讓你閱讀它,因爲我想讓你瞭解多部分郵件正文的結構:)我在代碼中發現了一些問題,請幫助我:) –

相關問題