2015-09-22 152 views
0

我需要上傳圖像到Web服務器,它需要ImageContent是在字節[]在文檔它說base64Binary的,但我想base64編碼字符串,沒有用安卓:通過HTTP GET或POST請求發送圖像的byte []

這是我的課:

private class background extends AsyncTask<byte[],Void,String> { 

    String url = "http://www.sample.com/_mobfiles/CLS_Account.asmx/UploadImage"; 
    String charset = "UTF-8"; 
    String param1 = "jpg"; 

    @Override 
    protected String doInBackground(byte[]... params) { 

     try { 
      String query = String.format("ImageContent=%s&imageExtenstion=%s", params[0], URLEncoder.encode(param2, charset)); 
      URLConnection connection = new URL(url + "?" + query).openConnection(); 
      connection.setRequestProperty("Accept-Charset", charset); 
      InputStream response = connection.getInputStream(); 
      for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { 
       System.out.println(header.getKey() + "=" + header.getValue()); 
      } 
      String contentType = connection.getHeaderField("Content-Type"); 
      String charset = null; 
      for (String param : contentType.replace(" ", "").split(";")) { 
       if (param.startsWith("charset=")) { 
        charset = param.split("=", 2)[1]; 
        break; 
       } 
      } 
      if (charset != null) { 
       try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) { 
        for (String line; (line = reader.readLine()) != null;) { 
         System.out.println(line); 
        } 
       } 
      } 
      else { 
       ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 
       int nRead; 
       byte[] data = new byte[16384]; 
       while ((nRead = response.read(data, 0, data.length)) != -1) { 
        buffer.write(data, 0, nRead); 
       } 
       buffer.flush(); 
       byte[] arr = buffer.toByteArray(); 
       String decoded = new String(arr, "UTF-8"); 
       System.out.println(decoded); 
      } 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return null; 
    } 
} 

返回(java.io.FileNotFoundException)

和Base64編碼的回報(java.net.ProtocolException:意外的狀態行:對象移動)

這裏是文件:


HTTP GET

以下是一個示例HTTP GET請求和響應。顯示的佔位符與實際值替換。

GET /_mobfiles/CLS_Account.asmx/UploadImage?ImageContent=base64Binary&imageExtenstion=string HTTP/1.1 
Host: www.sample.com 

和響應是象

HTTP/1.1 200 OK 
Content-Type: text/xml; charset=utf-8 
Content-Length: length 

<?xml version="1.0" encoding="utf-8"?> 
<string xmlns="http://tempuri.org/">string</string> 

HTTP POST

以下是一個示例HTTP POST請求和響應。顯示的佔位符與實際值替換。

POST /_mobfiles/CLS_Account.asmx/UploadImage HTTP/1.1 
Host: www.sample.com 
Content-Type: application/x-www-form-urlencoded 
Content-Length: length 

ImageContent=base64Binary&imageExtenstion=string 

和響應就像

HTTP/1.1 200 OK 
Content-Type: text/xml; charset=utf-8 
Content-Length: length 

<?xml version="1.0" encoding="utf-8"?> 
<string xmlns="http://tempuri.org/">string</string> 
+0

我應該在哪裏寫的是什麼? –

+0

嘗試在瀏覽器上嘗試,其中yyy指圖像類型,xxxx指向base64編碼圖像在此嘗試https://jsfiddle.net/o4mut2uv/並共享。使用小圖像快速。 – user1615664

+0

它顯示圖像ok –

回答

0

我還沒有找到一種方式,但在執行時從後臺線程AsyncTask我叫callSOAPWebService(String data)發送整個SOAP信封

所以

ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
Bitmap resizedBitmap = Bitmap.createScaledBitmap(thumbnail, 150, 150, false); 
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100,stream); 
byte[] byteArray = stream.toByteArray(); 
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT); 
new ImageUpload().execute(encoded); 
從UI線程

和背景

@Override 
     protected String doInBackground(String... params) { 
      callSOAPWebService(params[0]); 
      return null; 
     } 

callSOAPWebService是遵循

private boolean callSOAPWebService(String data) { 
     OutputStream out = null; 
     int respCode; 
     boolean isSuccess = false; 
     URL url; 
     HttpURLConnection httpURLConnection = null; 
     try { 
      url = new URL(GetData.NonOpDomain); 
      httpURLConnection = (HttpURLConnection) url.openConnection(); 
      do { 
       httpURLConnection.setRequestMethod("POST"); 
       httpURLConnection.setRequestProperty("Connection", "keep-alive"); 
       httpURLConnection.setRequestProperty("Content-Type", "text/xml"); 
       httpURLConnection.setRequestProperty("SendChunked", "True"); 
       httpURLConnection.setRequestProperty("UseCookieContainer", "True"); 
       HttpURLConnection.setFollowRedirects(false); 
       httpURLConnection.setDoOutput(true); 
       httpURLConnection.setDoInput(true); 
       httpURLConnection.setUseCaches(true); 
       httpURLConnection.setRequestProperty("Content-length", getReqData(data).length + ""); 
       httpURLConnection.setReadTimeout(100 * 1000); 
       // httpURLConnection.setConnectTimeout(10 * 1000); 
       httpURLConnection.connect(); 
       out = httpURLConnection.getOutputStream(); 
       if (out != null) { 
        out.write(getReqData(data)); 
        out.flush(); 
       } 
       respCode = httpURLConnection.getResponseCode(); 
       Log.e("respCode", ":" + respCode); 
      } while (respCode == -1); 

      // If it works fine 
      if (respCode == 200) { 
       try { 
        InputStream responce = httpURLConnection.getInputStream(); 
        String str = convertStreamToString(responce); 
        System.out.println(".....data....." + str); 
        InputStream is = new ByteArrayInputStream(str.getBytes("UTF-8")); 
        XmlPullParserFactory xmlFactoryObject = XmlPullParserFactory.newInstance(); 
        XmlPullParser myparser = xmlFactoryObject.newPullParser(); 
        myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); 
        myparser.setInput(is, null); 
        parseXMLAndStoreIt(myparser); 
       } catch (Exception e1) { 
        e1.printStackTrace(); 
       } 
      } else { 
       isSuccess = false; 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      if (out != null) { 
       out = null; 
      } 
      if (httpURLConnection != null) { 
       httpURLConnection.disconnect(); 
       httpURLConnection = null; 
      } 
     } 
     return isSuccess; 
    } 

和輔助方法

public volatile boolean parsingComplete = true; 

public void parseXMLAndStoreIt(XmlPullParser myParser) { 
    int event; 
    String text = null; 
    try { 
     event = myParser.getEventType(); 
     while (event != XmlPullParser.END_DOCUMENT) { 
      String name = myParser.getName(); 

      switch (event) { 
       case XmlPullParser.START_TAG: 
        break; 

       case XmlPullParser.TEXT: 
        text = myParser.getText(); 
        break; 
       case XmlPullParser.END_TAG: 
        if (name.equals("UploadImageResult")) { 
         uploadedImage = text; 
         uploadedImage = uploadedImage.replace("\"", ""); 
        } 
        break; 
      } 
      event = myParser.next(); 
     } 
     parsingComplete = false; 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

public static String createSoapHeader() { 
    String soapHeader; 

    soapHeader = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" 
      + "<soap:Envelope " 
      + "xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"" 
      + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" 
      + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" + ">"; 
    return soapHeader; 
} 

public static byte[] getReqData(String data) { 
    StringBuilder requestData = new StringBuilder(); 

    requestData.append(createSoapHeader()); 
    requestData.append("<soap:Body>" + "<UploadImage" + " xmlns=\"http://example.org/\">" + "<ImageContent>").append(data).append("</ImageContent>\n").append("<imageExtenstion>jpg</imageExtenstion>").append("</UploadImage> </soap:Body> </soap:Envelope>"); 
    Log.d("reqData: ", requestData.toString()); 
    return requestData.toString().trim().getBytes(); 
} 

private static String convertStreamToString(InputStream is) 
     throws UnsupportedEncodingException { 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, 
      "UTF-8")); 
    StringBuilder sb = new StringBuilder(); 
    String line; 
    try { 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      is.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return sb.toString(); 

} 

希望這將幫助一些人在未來

0

你可以試試這個在您的Chrome控制檯,並告訴輸出。

xmlhttp=new XMLHttpRequest(); 
    var url = '/_mobfiles/CLS_Account.asmx/UploadImage?'; 
    var base64 ='R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==' 
    xmlhttp.open("GET",url + 'ImageContent='+base64+'&imageExtenstion=gif',true); 
    xmlhttp.send(); 
    console.log(xmlhttp.response) 

也試試這個。如果這也失敗了,你必須檢查服務器。至少提供負責處理這個的服務器方法。

xmlhttp=new XMLHttpRequest(); 
var url = '/_mobfiles/CLS_Account.asmx/UploadImage?'; 
var base64 ='R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==' 
xmlhttp.open("POST",true); 
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
xmlhttp.send('ImageContent="'+base64+'"&imageExtenstion="gif"'); 
console.log(xmlhttp) 

使用GET請求,並使用

var base64 ='R0lGODlhDwAPAKECAAAAzMzM%2F%2F%2F%2F%2FwAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH%2BH09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw%3D%3D' 

我相信這應該工作。我真的很對不起我的壞,我應該還沒有做出這樣愚蠢的錯誤/

+0

GET http://www.sample.com/_mobfiles/CLS_Account.asmx/UploadImageTes...wWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==&imageExtenstion=gif 500(內部服務器錯誤) –

+0

狀態:404 狀態文本: 「OK」 上傳:XMLHttpRequestUpload withCredentials :假 __proto__:XMLHttpRequest的 –

+0

,並把當URL返回「System.ArgumentException:R0lGODlhDwAPAKECAAAAzMzM ///// wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN​​48CXF8m2iQ3YmmKqVlRtW4MLwWACH H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw ==無法轉換爲System.Byte 參數名:類型---> System.FormatException:輸入字符串沒有一個正確的格式。「 –