使用httpurlconnection类的图像上传问题

时间:2016-09-12 10:45:51

标签: android httpurlconnection

我正在使用此代码上传图像使用httpurlconnection class.in此代码图像上传成功并且我获取上传图像的路径作为响应但是当我尝试在浏览器中打开图像路径时,它会说图像包含错误

public class JSONParser {

private static JSONObject jobj = null;
private final String SERVER_PATH = "server url";

public JSONObject makeHttpRequest(String murl, Utils.method m, Map<String, String> parmas, String Token, String filepath, String filefield, String filemimetype){
    HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    InputStream inputStream = null;

    String twoHyphens = "--";
    String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****";
    String lineEnd = "\r\n";
    String urlTo = SERVER_PATH + murl;

    String result = "";

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    try {
        URL url = new URL(urlTo);
        connection = (HttpURLConnection) url.openConnection();

        connection.setUseCaches(false);
        if (m.equals(Utils.method.POST)) {
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
        } else if (m.equals(Utils.method.GET)){
            connection.setRequestMethod("GET");
        }
        connection.setRequestProperty("Connection", "Keep-Alive");
        /*connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");*/
        connection.setRequestProperty("User-Agent", "CodeJava Agent");
        connection.setRequestProperty("Accept","*/*");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        if (Token != null){
            connection.addRequestProperty("token", Token);
        }
          if (m.equals(Utils.method.POST)) {
            outputStream = new        DataOutputStream(connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        }
        if (filepath != null) {
            String[] q = filepath.split("/");
            int idx = q.length - 1;
            File file = new File(filepath);
            FileInputStream fileInputStream = new FileInputStream(file);
            outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] + "\"" + lineEnd);
            outputStream.writeBytes("Content-Type: " + filemimetype + lineEnd);
            outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                outputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            outputStream.writeBytes(lineEnd);
        }
//            outputStream.writeBytes(getQuery(parmas));
        if (m.equals(Utils.method.POST)) {
            if (!parmas.isEmpty()) {
                Iterator<String> keys = parmas.keySet().iterator();
                while (keys.hasNext()) {
                    String key = keys.next();
                    String value = parmas.get(key);
                    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                    outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd);
                    outputStream.writeBytes("Content-Type: text/plain" + lineEnd);
                    outputStream.writeBytes(lineEnd);
                    outputStream.writeBytes(value);
                    outputStream.writeBytes(lineEnd);
                }
                outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            }
        }

        inputStream = connection.getInputStream();

        result = this.convertStreamToString(inputStream);
        System.out.println("Response :"+result);
        jobj = new JSONObject(result);
        inputStream.close();
        if (m.equals(Utils.method.POST)) {
            outputStream.flush();
            outputStream.close();
        }
        connection.disconnect();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return jobj;
}

private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
  }

0 个答案:

没有答案