Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/182.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android:通过Http Get或Post请求以字节[]的形式发送图像_Java_Android_Soap_Httprequest - Fatal编程技术网

Java Android:通过Http Get或Post请求以字节[]的形式发送图像

Java Android:通过Http Get或Post请求以字节[]的形式发送图像,java,android,soap,httprequest,Java,Android,Soap,Httprequest,我需要将图像上传到web服务器,它要求ImageContent在文档中的字节[]中,它说的是base64Binary,但我尝试了base64编码字符串,但没有使用 ByteArrayOutputStream stream = new ByteArrayOutputStream(); Bitmap resizedBitmap = Bitmap.createScaledBitmap(thumbnail, 150, 150, false); resizedBitmap.compress(Bitmap.

我需要将图像上传到web服务器,它要求ImageContent在文档中的字节[]中,它说的是base64Binary,但我尝试了base64编码字符串,但没有使用

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);
那是我的班级:

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;
    }
}
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);
反应就像

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/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>
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);
反应就像

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

你能在你的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)
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);
也试试这个。如果这也失败了,你必须检查服务器。至少提供负责处理此问题的服务器方法

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)
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);
使用Get请求并使用

var base64 ='R0lGODlhDwAPAKECAAAAzMzM%2F%2F%2F%2F%2FwAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH%2BH09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw%3D%3D'
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);

我相信这应该行得通。我真的很抱歉,我不该犯这样一个愚蠢的错误/

我没有办法,只能把整个肥皂信封都寄出去

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);
因此,在后台线程AsyncTask中,我在执行时调用了callSOAPWebServiceString数据

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

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);
背景呢

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);
@Override
        protected String doInBackground(String... params) {
            callSOAPWebService(params[0]);
            return null;
        }
callSOAPWebService如下所示

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);
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;
    }
和助手方法

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

}

希望它能对将来的人有所帮助

我应该在哪里写呢?在浏览器上试试,yyy指的是图像类型,xxxx指的是base64编码的图像,在这里试试并分享。使用一个小图像来快速。它显示图像OK。您可以使用您的技术尝试一个1~KB左右的非常小的图像。这是谁的服务器?一般来说,GET请求有大小限制,而将图像转换为base 64本身会大幅增加大小,所以您的大小可能会有问题。尝试手动访问链接。预期的行为是什么?它应该返回包含自动生成的图像名称Get…wWACH+h09wdgltaxplzcbiesbvbgvhzcbtbfydfnhdmvyiqaaow==&imageExtenstion=gif 500的字符串对象的xml内部服务器错误状态:404状态文本:确定上载:XMLHttpRequestUpload with credentials:false proto:XMLHttpRequestand when putin url返回System.ArgumentException:无法将R0LGODLhdwapakecaaaaAaAaAaAaAaAaAaAaAaCiispeqhsrz5ModrlLn48cxf8m2iq3ymmkqvlrtw4mlwAch h09wdgltaxplzcbiesBvHzcBwFyDmVyQaaow==转换为System.Byte。参数名称:type-->System.FormatException:输入字符串的格式不正确。谢谢我的朋友,我将尝试与我的web提供商联系,我标记了答案是否有效?现在您应该只编码您的base64字符串。
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);