如何在Android中为http请求设置表单数据

时间:2014-03-03 09:37:40

标签: android http rest

这是用于上传文档的REST Api

请求网址

  

HTTP:UPLOAD_URL / {用户ID} /文件

方法类型

  

POST

标题

  

内容类型:应用/ JSON

网址变量

  

1. {userid} - 登录用户的唯一ID(例如VB000V)

form-data

  

{                    key:" file",value :, type:" file"                    key:" filepath",value:"",输入:" text"}

代码:

public class HttpUploadDoc extends AsyncTask<File, Void, String>{
    private HttpClient client;
    private HttpPost post;
    private HttpResponse response;
    private HttpEntity entity;
    private ProgressDialog mProgressDialog;
    private SharedPreferences sharedPreferences;

    int serverResponseCode=0;
    //for uploading..//
    String end = "\r\n";
    String twoHyphens = "--";
    String boundary = "******";

    private Context con;
    StringBuffer buffer=new StringBuffer();

    public HttpUploadDoc(Context con){
        this.con=con;
    }
    @Override
    protected void onPreExecute() {
        mProgressDialog=new ProgressDialog(con);
        mProgressDialog.setMessage("Loading");
        mProgressDialog.show();
        super.onPreExecute();
    }

    protected String doInBackground(File... params) {



        File file=params[0];

        String path=file.getAbsolutePath();

        FileBody fileBody=new FileBody(file);
        sharedPreferences=con.getSharedPreferences("LoginPref",Context.MODE_PRIVATE);
        String userId=sharedPreferences.getString("userid", "");

        client=new DefaultHttpClient();

        try {
            String filename=path.substring(path.lastIndexOf("/")+1);
            URL url = new URL(AllRestApiUrls.UploadDocument+userId+"/file");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setChunkedStreamingMode(128 * 1024);

            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setUseCaches(false);


            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/pdf");
            httpURLConnection.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            httpURLConnection.setRequestProperty("file",filename);
            httpURLConnection.setRequestProperty("filepath", path);

            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());

            String formdata="key=\"file\", value=\""
                    + filen+"\""+end
                +"key=\"filepath\",value=\""+path+"\"";
            dos.writeBytes(twoHyphens + boundary + end);
            dos.writeBytes("Content-Disposition: form-data; "+formdata);
            dos.writeBytes(end);


           FileInputStream fis = new FileInputStream(path);

            int bufferSize = 8 * 1024; // The size of the buffer, 8KB.
            byte[] buffer = new byte[bufferSize];
            int length = 0;

            while ((length = fis.read(buffer)) != -1) {


                // Write data to DataOutputStream
                dos.write(buffer, 0, length);
            }

            dos.writeBytes(end);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + end);

            fis.close(); // Close the FileInputStream.
            dos.flush(); // Flush the data to DataOutputStream.


            serverResponseCode = httpURLConnection.getResponseCode();
            String serverResponseMessage = httpURLConnection.getResponseMessage();

            Log.i("uploadFile", "HTTP Response is : "
                    + serverResponseMessage + ": " + serverResponseCode);




            entity.addPart("file", fileBody);
            FileInputStream input=new FileInputStream(f.getPath());
            entity.addPart("filepath", new StringBody(f.getAbsolutePath()));


            post.setEntity(entity);

             Intent intent = new Intent();
             intent.setAction(Intent.ACTION_VIEW);
             Uri uri = Uri.fromFile(f);
             intent.setDataAndType(uri, "application/pdf");
             con.startActivity(intent);


        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        }
        catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mProgressDialog.dismiss();

        return null;
    }




}

0 个答案:

没有答案