在android httpUrlConnection

时间:2016-02-16 07:05:31

标签: android

我正在将多页文件上传到php服务器 在服务器端,我没有从应用程序发出任何请求 但是当我在deffrent服务器上运行时,它可以工作

我尝试添加额外的标头,例如主机,用户代理,接受等......无法正常工作。

这是我的android代码:

import android.content.Context;
import android.provider.Settings;
import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

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

    public FileUploader(String requestURL, String charset,Context c) throws IOException {
        this.charset = charset;
        context = c;
        android_id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        // creates a unique boundary based on time stamp
        //boundary = "===" + System.currentTimeMillis() + "===";
        boundary = "===123456789===";

        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        // httpConn.setRequestMethod("POST");
        httpConn.setDoInput(true);
        httpConn.setRequestProperty("host", "genuinesell.com");
        httpConn.setRequestProperty("ACCEPT_LANGUAGE", "en-US, en;q=0.5");
        httpConn.setRequestProperty("CONNECTION", "keep-alive");
        httpConn.setRequestProperty("ACCEPT", "text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8");
        httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        httpConn.setRequestProperty("User-Agent",  "Mozilla/5.0 (compatible; U; ABrowse 0.6; Syllable) AppleWebKit/420+ (KHTML, like Gecko)");
        httpConn.setRequestProperty("id", android_id);
        outputStream = httpConn.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);
    }

    /**
     * Adds a form field to the request
     * @param name field name
     * @param value field value
     */
    public void addFormField(String name, String value) {
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
        .append(LINE_FEED);
        writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED);
        writer.append(LINE_FEED);
        writer.append(value).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Adds a upload file section to the request
     * @param fieldName name attribute in <input type="file" name="..." />
     * @param uploadFile a File to be uploaded
     * @throws IOException
     */
    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();

    }

    /**
     * Adds a header field to the request.
     * @param name - name of the header field
     * @param value - value of the header field
     */
    public void addHeaderField(String name, String value) {
        writer.append(name + ": " + value).append(LINE_FEED);
        writer.flush();
    }

    /**
     * Completes the request and receives response from the server.
     * @return a list of Strings as response in case the server returned
     * status OK, otherwise an exception is thrown.
     * @throws IOException
     */
    public List<String> finish() throws IOException {
        List<String> response = new ArrayList<String>();

        writer.append(LINE_FEED).flush();
        writer.append("--" + boundary + "--").append(LINE_FEED);
        writer.close();

        // checks server's status code first
        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) {
            response.add(line);
        }
        reader.close();
        httpConn.disconnect();
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }

        return response;
    }
}

这是日志

02-16 08:01:26.461 9934-9934/file.share.com.fileshare D/OpenGLRenderer: TextureCache::get: create texture(0xb9369640): name, size, mSize = 9, 1865956, 2788684
02-16 08:01:26.569 9934-9934/file.share.com.fileshare D/OpenGLRenderer: TextureCache::get: create texture(0xb9346ae8): name, size, mSize = 11, 36864, 2825548
02-16 08:01:26.573 9934-9934/file.share.com.fileshare D/OpenGLRenderer: TextureCache::get: create texture(0xb933ee98): name, size, mSize = 12, 36864, 2862412
02-16 08:01:26.609 9934-9934/file.share.com.fileshare D/OpenGLRenderer: TextureCache::get: create texture(0xb9356868): name, size, mSize = 13, 4096, 2866508
02-16 08:01:26.677 9934-9934/file.share.com.fileshare I/Choreographer: Skipped 37 frames!  The application may be doing too much work on its main thread.
02-16 08:01:26.857 9934-9936/file.share.com.fileshare D/dalvikvm: GC_CONCURRENT freed 605K, 5% free 16227K/16967K, paused 15ms+58ms, total 94ms
02-16 08:01:26.901 9934-9975/file.share.com.fileshare D/ssssssssss: default progress status ... 20
02-16 08:01:26.949 9934-9934/file.share.com.fileshare D/myHttpOnFinished: genuinesell.comfalse
02-16 08:01:26.949 9934-9934/file.share.com.fileshare D/ssssssssssss: herer is response genuinesell.comfalse
02-16 08:01:27.249 9934-9934/file.share.com.fileshare D/sssssss: genuinesell.cominvalid session id
02-16 08:01:44.773 9934-9934/file.share.com.fileshare I/dalvikvm: Could not find method android.widget.Spinner.getPopupContext, referenced from method android.support.v7.widget.AppCompatSpinner.getPopupContext
02-16 08:01:44.777 9934-9934/file.share.com.fileshare W/dalvikvm: VFY: unable to resolve virtual method 18951: Landroid/widget/Spinner;.getPopupContext ()Landroid/content/Context;
02-16 08:01:44.777 9934-9934/file.share.com.fileshare D/dalvikvm: VFY: replacing opcode 0x6f at 0x000b
02-16 08:01:44.781 9934-9934/file.share.com.fileshare I/dalvikvm: Could not find method android.content.Context.getDrawable, referenced from method android.support.v7.widget.AppCompatSpinner.setPopupBackgroundResource
02-16 08:01:44.789 9934-9934/file.share.com.fileshare W/dalvikvm: VFY: unable to resolve virtual method 302: Landroid/content/Context;.getDrawable (I)Landroid/graphics/drawable/Drawable;
02-16 08:01:44.789 9934-9934/file.share.com.fileshare D/dalvikvm: VFY: replacing opcode 0x6e at 0x0004
02-16 08:01:44.801 9934-9934/file.share.com.fileshare I/dalvikvm: Could not find method android.widget.PopupWindow.showAsDropDown, referenced from method android.support.v7.widget.AppCompatPopupWindow.showAsDropDown
02-16 08:01:44.809 9934-9934/file.share.com.fileshare W/dalvikvm: VFY: unable to resolve virtual method 18856: Landroid/widget/PopupWindow;.showAsDropDown (Landroid/view/View;III)V
02-16 08:01:44.809 9934-9934/file.share.com.fileshare D/dalvikvm: VFY: replacing opcode 0x6f at 0x000d
02-16 08:01:44.813 9934-9934/file.share.com.fileshare I/dalvikvm: Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawable
02-16 08:01:44.821 9934-9934/file.share.com.fileshare W/dalvikvm: VFY: unable to resolve virtual method 453: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
02-16 08:01:44.821 9934-9934/file.share.com.fileshare D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
02-16 08:01:44.825 9934-9934/file.share.com.fileshare I/dalvikvm: Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawableForDensity
02-16 08:01:44.825 9934-9934/file.share.com.fileshare W/dalvikvm: VFY: unable to resolve virtual method 455: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
02-16 08:01:44.829 9934-9934/file.share.com.fileshare D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
02-16 08:01:44.897 9934-9934/file.share.com.fileshare E/dalvikvm: Could not find class 'android.widget.ThemedSpinnerAdapter', referenced from method android.support.v7.widget.AppCompatSpinner$DropDownAdapter.<init>
02-16 08:01:44.897 9934-9934/file.share.com.fileshare W/dalvikvm: VFY: unable to resolve instanceof 2219 (Landroid/widget/ThemedSpinnerAdapter;) in Landroid/support/v7/widget/AppCompatSpinner$DropDownAdapter;
02-16 08:01:44.901 9934-9934/file.share.com.fileshare D/dalvikvm: VFY: replacing opcode 0x20 at 0x0016
02-16 08:01:45.025 9934-9934/file.share.com.fileshare W/EGL_genymotion: eglSurfaceAttrib not implemented
02-16 08:01:45.105 9934-9934/file.share.com.fileshare D/OpenGLRenderer: TextureCache::get: create texture(0xb9355b48): name, size, mSize = 30, 52900, 2919408
02-16 08:01:45.117 9934-9934/file.share.com.fileshare D/OpenGLRenderer: TextureCache::get: create texture(0xb93f5e40): name, size, mSize = 31, 322588, 3241996
02-16 08:01:45.173 9934-9934/file.share.com.fileshare D/OpenGLRenderer: TextureCache::get: create texture(0xb938d170): name, size, mSize = 32, 6912, 3248908
02-16 08:01:45.381 9934-9934/file.share.com.fileshare D/OpenGLRenderer: TextureCache::get: create texture(0xb93f68b8): name, size, mSize = 35, 45796, 3294704
02-16 08:01:45.421 9934-9934/file.share.com.fileshare D/OpenGLRenderer: TextureCache::get: create texture(0xb93f6d98): name, size, mSize = 36, 256688, 3551392
02-16 08:01:46.929 9934-9934/file.share.com.fileshare D/ssssssss: link one http://genuinesell.com/fileshare/index.php/story/create_new/
02-16 08:01:47.805 9934-10231/file.share.com.fileshare W/System.err: java.io.IOException: Server returned non-OK status: 400

0 个答案:

没有答案