2016-03-15 101 views
2

PostmanSnapshot安卓:在服务器

HttpURLConnection conn = null; 
    DataOutputStream dos = null; 
    DataInputStream inStream = null; 
    String lineEnd = "\r\n"; 
    String twoHyphens = "--"; 
    String boundary = "*****"; 
    int bytesRead, bytesAvailable, bufferSize; 
    byte[] buffer; 
    int maxBufferSize = 1 * 1024 * 1024; 
    try { 
    FileInputStream fileInputStream = new FileInputStream(new File(selectedPath)); 
    URL url = new URL(UPLOAD_URL); 
    conn = (HttpURLConnection) url.openConnection(); 
    conn.setDoInput(true); 
    conn.setDoOutput(true); 
    conn.setRequestMethod("POST"); 
    conn.setRequestProperty("authToken", authToken); 
    conn.setRequestProperty("Connection", "Keep-Alive"); 
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); 

    dos = new DataOutputStream(conn.getOutputStream()); 
    dos.writeBytes(lineEnd+twoHyphens + boundary + lineEnd); 
    dos.writeBytes("Content-Disposition: form-data; name:\"photo-0\";filename=\"" + selectedPath + "\"" + lineEnd); 
    dos.writeBytes("Content-Type: multipart/form-data"+lineEnd+lineEnd); 
    dos.writeBytes(lineEnd); 
    bytesAvailable = fileInputStream.available(); 
    bufferSize = Math.min(bytesAvailable, maxBufferSize); 
    buffer = new byte[bufferSize]; 

    bytesRead = bytesAvailable; 

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

    dos.writeBytes(lineEnd); 
    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 
    fileInputStream.close(); 
    dos.flush(); 
    dos.close(); 

    } catch (MalformedURLException ex) { 
    Log.e("Debug", "error: " + ex.getMessage(), ex); 
    } catch (IOException ioe) { 
    Log.e("Debug", "error: " + ioe.getMessage(), ioe); 
    } 
    try { 
    inStream = new DataInputStream (conn.getInputStream()); 
    String str; 

    while ((str = inStream.readLine()) != null) 
    { 
    Log.e("Debug","Server Response "+str); 
    } 
    inStream.close(); 

    } 
    catch (IOException ioex){ 
    Log.e("Debug", "error: " + ioex.getMessage(), ioex); 
    } 

此代码是从Android应用程序上传服务器上的文件上传文件。 运行代码时服务器状态为true,但不通过服务器发送文件。 我附上邮递员快照。授权码在标题中发送。

请帮

+0

你有任何错误日志? – Yazan

+0

不,只有这样:E/Debug:写入文件 /System.out:[OKHttp] sendRequest >> System.out:[OkHttp] sendRequest << E/Debug:Server Response {“status”:true} –

+0

'bytesRead = bytesAvailable;'这当然不好。引入一个'totalbytesread'和'totalbyteswritten'变量,然后与bytesAvailable和文件大小进行比较。请注意四个值。 – greenapps

回答

1

我发现了一些东西,可能会帮助谁正在寻找同样的问题。 它正在工作。我在做错的是在while循环中。

public class MultipartUtility { 
private final String boundary; 
private static final String LINE_FEED = "\r\n"; 
private HttpURLConnection httpConn; 
private String charset; 
private OutputStream outputStream; 
private PrintWriter writer; 

public MultipartUtility(String requestURL, String charset) 
     throws IOException { 
    this.charset = charset; 
    boundary = "===" + System.currentTimeMillis() + "==="; 
    URL url = new URL(requestURL); 
    httpConn = (HttpURLConnection) url.openConnection(); 
    httpConn.setUseCaches(false); 
    httpConn.setDoOutput(true); // indicates POST method 
    httpConn.setDoInput(true); 
    httpConn.setConnectTimeout(10000);//10 sec timeout 
    httpConn.setRequestProperty("Content-Type","multipart/form-data;  boundary=" + boundary); 
    httpConn.setRequestProperty("authToken", LoginActivity.authenticationToken); 
    outputStream = httpConn.getOutputStream(); 
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true); 
} 

public void addFilePart(String fieldName, File uploadFile) throws IOException { 
    String fileName = uploadFile.getName(); 
    writer.append("--" + boundary).append(LINE_FEED); 
    writer.append("Content-Disposition: form-data; name=\"" + fieldName+ "\"; filename=\"" + fileName + "\"").append(LINE_FEED); 
    writer.append("Content-Type: "+ URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED); 
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED); 
    writer.append(LINE_FEED); 
    writer.flush(); 
    FileInputStream inputStream = new FileInputStream(uploadFile); 
    byte[] buffer = new byte[4096]; 
    int bytesRead = -1; 
    while ((bytesRead = inputStream.read(buffer)) != -1) { 
     outputStream.write(buffer, 0, bytesRead); 
    } 
    outputStream.flush(); 
    inputStream.close(); 
    writer.append(LINE_FEED); 
    writer.flush(); 
} 

public String finish() throws IOException { 
    StringBuilder sb = new StringBuilder(); 
    writer.append(LINE_FEED).flush(); 
    writer.append("--" + boundary + "--").append(LINE_FEED); 
    writer.close(); 
    int status = httpConn.getResponseCode(); 
    if (status == HttpURLConnection.HTTP_OK) { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     reader.close(); 
     httpConn.disconnect(); 
    } else { 
     throw new IOException("Server returned non-OK status: " + status); 
    } 
    return sb.toString(); 
} 

}

+0

您应该为您找到的代码提供归属。 (似乎来自[这里](http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically)。) – Mogsdad

+0

@Mogsdad有很多资源提供此代码。其实我发现这个在stackoverflow答案。 –

+0

很棒... _which_答案? (他们缺乏归因是一个不同的问题。)但是更重要的是,你的问题可能是重复的,正确的做法是把它作为这个问题的重复。那么具有相同问题的未来人将会找到他们的答案。 – Mogsdad