POST请求与android

时间:2014-08-07 14:11:14

标签: java php android

我是Android开发的新手。我有这个代码用PHP发送一个POST请求到服务器。

HttpURLConnection conn;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = Long.toHexString(System.currentTimeMillis());
File sourceFile = new File(sourceFileUri);

if (!sourceFile.isFile()) {

    dialog.dismiss();

    Log.e(MainActivity.TAG, "Source File not exist :" + imagepath);
    uploadButton.setEnabled(true);
    return 0;

} else {
    try {

        postName = "Filedata[]";
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);

        // Open a HTTP  connection to  the URL
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");

        String cookie = CookieManager.getInstance().getCookie(upLoadServerUri);
        conn.setRequestProperty("Cookie", cookie);
        conn.setRequestProperty("User-Agent", MainActivity.userAgent);

        conn.setRequestProperty("Connection", "Keep-Alive");


        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty(postName, sourceFileUri);

        String charset = "UTF-8";
        OutputStream output = conn.getOutputStream();

        PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);

        // Send normal param.
        writer.append(twoHyphens).append(boundary).append(lineEnd);
        writer.append("Content-Disposition: form-data; name=\"to\"").append(lineEnd);
        writer.append("Content-Type: text/plain; charset=").append(charset).append(lineEnd);
        writer.append(lineEnd).append(id).append(lineEnd).flush();

        writer.append(twoHyphens).append(boundary).append(lineEnd);
        writer.append("Content-Disposition: form-data; name=\"content\"").append(lineEnd);
        writer.append("Content-Type: text/plain; charset=").append(charset).append(lineEnd);
        writer.append(lineEnd).append("image").append(lineEnd).flush();

        // Send the picture
        writer.append(twoHyphens).append(boundary).append(lineEnd);
        writer.append("Content-Disposition: form-data; name=\"" + postName + "\"; filename=\"" + sourceFileUri + "\"").append(lineEnd);
        writer.append("Content-Type: ").append(HttpURLConnection.guessContentTypeFromName(sourceFileUri)).append(lineEnd);
        writer.append("Content-Transfer-Encoding: binary").append(lineEnd);
        writer.append(lineEnd).flush();
        copyFile(fileInputStream, output);
        output.flush();
        writer.append(lineEnd).flush();

        // End of multipart/form-data.
        writer.append(twoHyphens).append(boundary).append(twoHyphens).append(lineEnd);


        // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        //  final String serverResponseMessage = conn.getResponseMessage();
        InputStream stream = conn.getInputStream();
        InputStreamReader isReader = new InputStreamReader(stream);

        // put output stream into a string
        BufferedReader br = new BufferedReader(isReader);
        String serverResponsePre = "";
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
            serverResponsePre += line;
        }

        final String serverResponse = serverResponsePre;


        if (serverResponseCode == 200) {
            Toast.makeText(Uploader.this, "File Upload Complete:" + serverResponse, Toast.LENGTH_LONG).show();
        }
        fileInputStream.close();
        this.finish();

}catch(MalformedURLException ex){

    dialog.dismiss();
    ex.printStackTrace();

    Log.e(MainActivity.TAG, "error: " + ex.getMessage(), ex);
    uploadButton.setEnabled(true);
}catch(Exception e){

    dialog.dismiss();
    e.printStackTrace();
    Toast.makeText(Uploader.this, "Got Exception : see logcat ", Toast.LENGTH_LONG).show();
    Log.e(MainActivity.TAG, "Exception : " + e.getMessage(), e);
    uploadButton.setEnabled(true);
}
dialog.dismiss();

private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
        out.write(buffer, 0, read);
    }
}

在android方面,不会抛出任何错误。在PHP端,设置了$ _FILES [“Filedata”],但文件大小为0且未设置tmp_name。我错过了什么吗?我无法发现错误。提前谢谢。

0 个答案:

没有答案