Example usage for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE

List of usage examples for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE

Introduction

In this page you can find the example usage for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE.

Prototype

HttpMultipartMode BROWSER_COMPATIBLE

To view the source code for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE.

Click Source Link

Usage

From source file:com.groupon.odo.bmp.http.BrowserMobHttpRequest.java

public void makeMultiPart() {
    if (!multiPart) {
        multiPart = true;//  w ww  .  j a  v a2 s .  co  m
        multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    }
}

From source file:com.cloverstudio.spika.couchdb.ConnectionHandler.java

public static String getIdFromFileUploader(String url, List<NameValuePair> params)
        throws ClientProtocolException, IOException, UnsupportedOperationException, SpikaException,
        JSONException {/*  ww  w .  j a va 2  s .c  o  m*/
    // Making HTTP request

    // defaultHttpClient
    HttpParams httpParams = new BasicHttpParams();
    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
    HttpClient httpClient = new DefaultHttpClient(httpParams);
    HttpPost httpPost = new HttpPost(url);

    httpPost.setHeader("database", Const.DATABASE);

    Charset charSet = Charset.forName("UTF-8"); // Setting up the
    // encoding

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (int index = 0; index < params.size(); index++) {
        if (params.get(index).getName().equalsIgnoreCase(Const.FILE)) {
            // If the key equals to "file", we use FileBody to
            // transfer the data
            entity.addPart(params.get(index).getName(), new FileBody(new File(params.get(index).getValue())));
        } else {
            // Normal string data
            entity.addPart(params.get(index).getName(), new StringBody(params.get(index).getValue(), charSet));
        }
    }

    httpPost.setEntity(entity);

    print(httpPost);

    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    InputStream is = httpEntity.getContent();

    //      if (httpResponse.getStatusLine().getStatusCode() > 400)
    //      {
    //         if (httpResponse.getStatusLine().getStatusCode() == 500) throw new SpikaException(ConnectionHandler.getError(entity.getContent()));
    //         throw new IOException(httpResponse.getStatusLine().getReasonPhrase());
    //      }

    // BufferedReader reader = new BufferedReader(new
    // InputStreamReader(is, "iso-8859-1"), 8);
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    is.close();
    String json = sb.toString();

    Logger.debug("RESPONSE", json);

    return json;
}

From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry7.QMetryRestWebservice.java

public int attachTestLogs(long tcVersionIdASEntityId, File filePath) {
    try {//from   w  ww  .  j av  a2  s.c  o  m
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss");

        final String CurrentDate = format.format(new Date());
        Path path = Paths.get(filePath.toURI());
        byte[] outFileArray = Files.readAllBytes(path);

        if (outFileArray != null) {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                HttpPost httppost = new HttpPost(serviceUrl + "/rest/attachments");

                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

                FileBody bin = new FileBody(filePath);
                builder.addPart("file", bin);

                HttpEntity reqEntity = builder.build();
                httppost.setEntity(reqEntity);
                httppost.addHeader("usertoken", token);
                httppost.addHeader("scope", scope);

                CloseableHttpResponse response = httpclient.execute(httppost);
                String str = null;
                try {
                    str = EntityUtils.toString(response.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }
                JsonElement gson = new Gson().fromJson(str, JsonElement.class);
                JsonElement data = gson.getAsJsonObject().get("data");
                int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString());
                return id;
            } finally {
                httpclient.close();
            }
        } else {
            System.out.println(filePath + " file does not exists");
        }
    } catch (Exception ex) {
        System.out.println("Error in attaching file - " + filePath);
        System.out.println(ex.getMessage());
    }
    return 0;
}

From source file:it.restrung.rest.client.DefaultRestClientImpl.java

/**
 * Private helper to setup a multipart request body
 *///  ww  w . j  a va2s . co  m
private static void setupMultipartBodyWithFile(HttpEntityEnclosingRequestBase httpEntityEnclosingRequestBase,
        APIPostParams apiPostParams, String body, File file) throws UnsupportedEncodingException {
    //MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    CountingMultipartEntity mpEntity = new CountingMultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
            Charset.forName("UTF-8"), file != null ? body.length() + file.length() : body.length(),
            apiPostParams);
    mpEntity.addPart("body", new StringBody(body, Charset.forName("UTF-8")));
    if (file != null) {
        FileBody uploadFilePart = new FileBody(file, "application/octet-stream");
        mpEntity.addPart("file", uploadFilePart);
    }
    httpEntityEnclosingRequestBase.setHeader(mpEntity.getContentType());
    httpEntityEnclosingRequestBase.setEntity(mpEntity);
}

From source file:io.andyc.papercut.api.PrintApi.java

/**
 * Uploads the file and finalizes the printing
 *
 * @param printJob    {PrintJob} - the print job
 * @param prevElement {Element} - the previous Jsoup element containing the
 *                    upload file Html/* w w w .j  a va  2 s  .co  m*/
 *
 * @return {boolean} - whether or not the print job completed
 */
static boolean uploadFile(PrintJob printJob, Document prevElement)
        throws PrintingException, UnsupportedMimeTypeException {
    String uploadUrl = printJob.getSession().getDomain().replace("/app", "")
            + PrintApi.getUploadFileUrl(prevElement); // upload directory

    HttpPost post = new HttpPost(uploadUrl);
    CloseableHttpClient client = HttpClientBuilder.create().build();

    // configure multipart post request entity builder
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    // build the file boundary
    String boundary = "-----------------------------" + new Date().getTime();
    entityBuilder.setBoundary(boundary);

    // set the file
    File file = new File(printJob.getFilePath());
    FileBody body = new FileBody(file,
            ContentType.create(ContentTypes.getApplicationType(printJob.getFilePath())), file.getName());
    entityBuilder.addPart("file[]", body);

    // build the post request
    HttpEntity multipart = entityBuilder.build();
    post.setEntity(multipart);

    // set cookie
    post.setHeader("Cookie", printJob.getSession().getSessionKey() + "=" + printJob.getSession().getSession());

    // send
    try {
        CloseableHttpResponse response = client.execute(post);
        return response.getStatusLine().getStatusCode() == 200;
    } catch (IOException e) {
        throw new PrintingException("Error uploading the file");
    }
}

From source file:com.portfolio.data.attachment.XSLService.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    /**/*from   ww w. j  a  va 2 s . c  o  m*/
     * Format demand:
     * <convert>
     *   <portfolioid>{uuid}</portfolioid>
     *   <portfolioid>{uuid}</portfolioid>
     *   <nodeid>{uuid}</nodeid>
     *   <nodeid>{uuid}</nodeid>
     *   <documentid>{uuid}</documentid>
     *   <xsl>{rpertoire}{fichier}</xsl>
     *   <format>[pdf rtf xml ...]</format>
     *   <parameters>
     *     <maVar1>lala</maVar1>
     *     ...
     *   </parameters>
     * </convert>
     */
    try {
        //On initialise le dataProvider
        Connection c = null;
        //On initialise le dataProvider
        if (ds == null) // Case where we can't deploy context.xml
        {
            c = getConnection();
        } else {
            c = ds.getConnection();
        }
        dataProvider.setConnection(c);
        credential = new Credential(c);
    } catch (Exception e) {
        e.printStackTrace();
    }

    String origin = request.getRequestURL().toString();

    /// Variable stuff
    int userId = 0;
    int groupId = 0;
    String user = "";
    HttpSession session = request.getSession(true);
    if (session != null) {
        Integer val = (Integer) session.getAttribute("uid");
        if (val != null)
            userId = val;
        val = (Integer) session.getAttribute("gid");
        if (val != null)
            groupId = val;
        user = (String) session.getAttribute("user");
    }

    /// TODO: A voire si un form get ne ferait pas l'affaire aussi

    /// On lis le xml
    /*
    BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while( (line = rd.readLine()) != null )
       sb.append(line);
            
    DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = null;
    Document doc=null;
    try
    {
       documentBuilder = documentBuilderFactory.newDocumentBuilder();
       doc = documentBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes("UTF-8")));
    }
    catch( Exception e )
    {
       e.printStackTrace();
    }
            
    /// On lit les paramtres
    NodeList portfolioNode = doc.getElementsByTagName("portfolioid");
    NodeList nodeNode = doc.getElementsByTagName("nodeid");
    NodeList documentNode = doc.getElementsByTagName("documentid");
    NodeList xslNode = doc.getElementsByTagName("xsl");
    NodeList formatNode = doc.getElementsByTagName("format");
    NodeList parametersNode = doc.getElementsByTagName("parameters");
    //*/
    //      String xslfile = xslNode.item(0).getTextContent();
    String xslfile = request.getParameter("xsl");
    String format = request.getParameter("format");
    //      String format = formatNode.item(0).getTextContent();
    String parameters = request.getParameter("parameters");
    String documentid = request.getParameter("documentid");
    String portfolios = request.getParameter("portfolioids");
    String[] portfolioid = null;
    if (portfolios != null)
        portfolioid = portfolios.split(";");
    String nodes = request.getParameter("nodeids");
    String[] nodeid = null;
    if (nodes != null)
        nodeid = nodes.split(";");

    System.out.println("PARAMETERS: ");
    System.out.println("xsl: " + xslfile);
    System.out.println("format: " + format);
    System.out.println("user: " + userId);
    System.out.println("portfolioids: " + portfolios);
    System.out.println("nodeids: " + nodes);
    System.out.println("parameters: " + parameters);

    boolean redirectDoc = false;
    if (documentid != null) {
        redirectDoc = true;
        System.out.println("documentid @ " + documentid);
    }

    boolean usefop = false;
    String ext = "";
    if (MimeConstants.MIME_PDF.equals(format)) {
        usefop = true;
        ext = ".pdf";
    } else if (MimeConstants.MIME_RTF.equals(format)) {
        usefop = true;
        ext = ".rtf";
    }
    //// Paramtre portfolio-uuid et file-xsl
    //      String uuid = request.getParameter("uuid");
    //      String xslfile = request.getParameter("xsl");

    StringBuilder aggregate = new StringBuilder();
    try {
        int portcount = 0;
        int nodecount = 0;
        // On aggrge les donnes
        if (portfolioid != null) {
            portcount = portfolioid.length;
            for (int i = 0; i < portfolioid.length; ++i) {
                String p = portfolioid[i];
                String portfolioxml = dataProvider
                        .getPortfolio(new MimeType("text/xml"), p, userId, groupId, "", null, null, 0)
                        .toString();
                aggregate.append(portfolioxml);
            }
        }

        if (nodeid != null) {
            nodecount = nodeid.length;
            for (int i = 0; i < nodeid.length; ++i) {
                String n = nodeid[i];
                String nodexml = dataProvider.getNode(new MimeType("text/xml"), n, true, userId, groupId, "")
                        .toString();
                aggregate.append(nodexml);
            }
        }

        // Est-ce qu'on a eu besoin d'aggrger les donnes?
        String input = aggregate.toString();
        String pattern = "<\\?xml[^>]*>"; // Purge previous xml declaration

        input = input.replaceAll(pattern, "");

        input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!DOCTYPE xsl:stylesheet ["
                + "<!ENTITY % lat1 PUBLIC \"-//W3C//ENTITIES Latin 1 for XHTML//EN\" \"" + servletDir
                + "xhtml-lat1.ent\">" + "<!ENTITY % symbol PUBLIC \"-//W3C//ENTITIES Symbols for XHTML//EN\" \""
                + servletDir + "xhtml-symbol.ent\">"
                + "<!ENTITY % special PUBLIC \"-//W3C//ENTITIES Special for XHTML//EN\" \"" + servletDir
                + "xhtml-special.ent\">" + "%lat1;" + "%symbol;" + "%special;" + "]>" + // For the pesky special characters
                "<root>" + input + "</root>";

        //         System.out.println("INPUT WITH PROXY:"+ input);

        /// Rsolution des proxys
        DocumentBuilder documentBuilder;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader(input));
        Document doc = documentBuilder.parse(is);

        /// Proxy stuff
        XPath xPath = XPathFactory.newInstance().newXPath();
        String filterRes = "//asmResource[@xsi_type='Proxy']";
        String filterCode = "./code/text()";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

        XPathExpression codeFilter = xPath.compile(filterCode);

        for (int i = 0; i < nodelist.getLength(); ++i) {
            Node res = nodelist.item(i);
            Node gp = res.getParentNode(); // resource -> context -> container
            Node ggp = gp.getParentNode();
            Node uuid = (Node) codeFilter.evaluate(res, XPathConstants.NODE);

            /// Fetch node we want to replace
            String returnValue = dataProvider
                    .getNode(new MimeType("text/xml"), uuid.getTextContent(), true, userId, groupId, "")
                    .toString();

            Document rep = documentBuilder.parse(new InputSource(new StringReader(returnValue)));
            Element repNode = rep.getDocumentElement();
            Node proxyNode = repNode.getFirstChild();
            proxyNode = doc.importNode(proxyNode, true); // adoptNode have some weird side effect. To be banned
            //            doc.replaceChild(proxyNode, gp);
            ggp.insertBefore(proxyNode, gp); // replaceChild doesn't work.
            ggp.removeChild(gp);
        }

        try // Convert XML document to string
        {
            DOMSource domSource = new DOMSource(doc);
            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer transformer = tf.newTransformer();
            transformer.transform(domSource, result);
            writer.flush();
            input = writer.toString();
        } catch (TransformerException ex) {
            ex.printStackTrace();
        }

        //         System.out.println("INPUT DATA:"+ input);

        // Setup a buffer to obtain the content length
        ByteArrayOutputStream stageout = new ByteArrayOutputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        //// Setup Transformer (1st stage)
        /// Base path
        String basepath = xslfile.substring(0, xslfile.indexOf(File.separator));
        String firstStage = baseDir + File.separator + basepath + File.separator + "karuta" + File.separator
                + "xsl" + File.separator + "html2xml.xsl";
        System.out.println("FIRST: " + firstStage);
        Source xsltSrc1 = new StreamSource(new File(firstStage));
        Transformer transformer1 = transFactory.newTransformer(xsltSrc1);
        StreamSource stageSource = new StreamSource(new ByteArrayInputStream(input.getBytes()));
        Result stageRes = new StreamResult(stageout);
        transformer1.transform(stageSource, stageRes);

        // Setup Transformer (2nd stage)
        String secondStage = baseDir + File.separator + xslfile;
        Source xsltSrc2 = new StreamSource(new File(secondStage));
        Transformer transformer2 = transFactory.newTransformer(xsltSrc2);

        // Configure parameter from xml
        String[] table = parameters.split(";");
        for (int i = 0; i < table.length; ++i) {
            String line = table[i];
            int var = line.indexOf(":");
            String par = line.substring(0, var);
            String val = line.substring(var + 1);
            transformer2.setParameter(par, val);
        }

        // Setup input
        StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(stageout.toString().getBytes()));
        //         StreamSource xmlSource = new StreamSource(new File(baseDir+origin, "projectteam.xml") );

        Result res = null;
        if (usefop) {
            /// FIXME: Might need to include the entity for html stuff?
            //Setup FOP
            //Make sure the XSL transformation's result is piped through to FOP
            Fop fop = fopFactory.newFop(format, out);

            res = new SAXResult(fop.getDefaultHandler());

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        } else {
            res = new StreamResult(out);

            //Start the transformation and rendering process
            transformer2.transform(xmlSource, res);
        }

        if (redirectDoc) {

            // /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]]
            String urlTarget = "http://" + server + "/resources/resource/file/" + documentid;
            System.out.println("Redirect @ " + urlTarget);

            HttpClientBuilder clientbuilder = HttpClientBuilder.create();
            CloseableHttpClient client = clientbuilder.build();

            HttpPost post = new HttpPost(urlTarget);
            post.addHeader("referer", origin);
            String sessionid = request.getSession().getId();
            System.out.println("Session: " + sessionid);
            post.addHeader("Cookie", "JSESSIONID=" + sessionid);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            ByteArrayBody body = new ByteArrayBody(out.toByteArray(), "generated" + ext);

            builder.addPart("uploadfile", body);

            HttpEntity entity = builder.build();
            post.setEntity(entity);
            HttpResponse ret = client.execute(post);
            String stringret = new BasicResponseHandler().handleResponse(ret);

            int code = ret.getStatusLine().getStatusCode();
            response.setStatus(code);
            ServletOutputStream output = response.getOutputStream();
            output.write(stringret.getBytes(), 0, stringret.length());
            output.close();
            client.close();

            /*
            HttpURLConnection connection = CreateConnection( urlTarget, request );
                    
            /// Helping construct Json
            connection.setRequestProperty("referer", origin);
                    
            /// Send post data
            ServletInputStream inputData = request.getInputStream();
            DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
                    
            byte[] buffer = new byte[1024];
            int dataSize;
            while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
            {
               writer.write(buffer, 0, dataSize);
            }
            inputData.close();
            writer.close();
                    
            RetrieveAnswer(connection, response, origin);
            //*/
        } else {
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=generated" + ext);
            response.setContentType(format);
            response.setContentLength(out.size());
            response.getOutputStream().write(out.toByteArray());
            response.getOutputStream().flush();
        }
    } catch (Exception e) {
        String message = e.getMessage();
        response.setStatus(500);
        response.getOutputStream().write(message.getBytes());
        response.getOutputStream().close();

        e.printStackTrace();
    } finally {
        dataProvider.disconnect();
    }
}

From source file:org.eweb4j.spiderman.plugin.util.PageFetcherImpl.java

/**
 * //  w ww  . j a v  a  2  s.  c o  m
 * @date 2013-1-7 ?11:08:54
 * @param toFetchURL
 * @return
 */
public FetchResult request(FetchRequest req) throws Exception {
    FetchResult fetchResult = new FetchResult();
    HttpUriRequest request = null;
    HttpEntity entity = null;
    String toFetchURL = req.getUrl();
    boolean isPost = false;
    try {
        if (Http.Method.GET.equalsIgnoreCase(req.getHttpMethod()))
            request = new HttpGet(toFetchURL);
        else if (Http.Method.POST.equalsIgnoreCase(req.getHttpMethod())) {
            request = new HttpPost(toFetchURL);
            isPost = true;
        } else if (Http.Method.PUT.equalsIgnoreCase(req.getHttpMethod()))
            request = new HttpPut(toFetchURL);
        else if (Http.Method.HEAD.equalsIgnoreCase(req.getHttpMethod()))
            request = new HttpHead(toFetchURL);
        else if (Http.Method.OPTIONS.equalsIgnoreCase(req.getHttpMethod()))
            request = new HttpOptions(toFetchURL);
        else if (Http.Method.DELETE.equalsIgnoreCase(req.getHttpMethod()))
            request = new HttpDelete(toFetchURL);
        else
            throw new Exception("Unknown http method name");

        //???,??
        // TODO ?delay?
        synchronized (mutex) {
            //??
            long now = (new Date()).getTime();
            //?Host??
            if (now - lastFetchTime < config.getPolitenessDelay())
                Thread.sleep(config.getPolitenessDelay() - (now - lastFetchTime));
            //????HOST??URL
            lastFetchTime = (new Date()).getTime();
        }

        //GZIP???GZIP?
        request.addHeader("Accept-Encoding", "gzip");
        for (Iterator<Entry<String, String>> it = headers.entrySet().iterator(); it.hasNext();) {
            Entry<String, String> entry = it.next();
            request.addHeader(entry.getKey(), entry.getValue());
        }

        //?
        Header[] headers = request.getAllHeaders();
        for (Header h : headers) {
            Map<String, List<String>> hs = req.getHeaders();
            String key = h.getName();
            List<String> val = hs.get(key);
            if (val == null)
                val = new ArrayList<String>();
            val.add(h.getValue());

            hs.put(key, val);
        }
        req.getCookies().putAll(this.cookies);
        fetchResult.setReq(req);

        HttpEntity reqEntity = null;
        if (Http.Method.POST.equalsIgnoreCase(req.getHttpMethod())
                || Http.Method.PUT.equalsIgnoreCase(req.getHttpMethod())) {
            if (!req.getFiles().isEmpty()) {
                reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                for (Iterator<Entry<String, List<File>>> it = req.getFiles().entrySet().iterator(); it
                        .hasNext();) {
                    Entry<String, List<File>> e = it.next();
                    String paramName = e.getKey();
                    for (File file : e.getValue()) {
                        // For File parameters
                        ((MultipartEntity) reqEntity).addPart(paramName, new FileBody(file));
                    }
                }

                for (Iterator<Entry<String, List<Object>>> it = req.getParams().entrySet().iterator(); it
                        .hasNext();) {
                    Entry<String, List<Object>> e = it.next();
                    String paramName = e.getKey();
                    for (Object paramValue : e.getValue()) {
                        // For usual String parameters
                        ((MultipartEntity) reqEntity).addPart(paramName, new StringBody(
                                String.valueOf(paramValue), "text/plain", Charset.forName("UTF-8")));
                    }
                }
            } else {
                List<NameValuePair> params = new ArrayList<NameValuePair>(req.getParams().size());
                for (Iterator<Entry<String, List<Object>>> it = req.getParams().entrySet().iterator(); it
                        .hasNext();) {
                    Entry<String, List<Object>> e = it.next();
                    String paramName = e.getKey();
                    for (Object paramValue : e.getValue()) {
                        params.add(new BasicNameValuePair(paramName, String.valueOf(paramValue)));
                    }
                }
                reqEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
            }

            if (isPost)
                ((HttpPost) request).setEntity(reqEntity);
            else
                ((HttpPut) request).setEntity(reqEntity);
        }

        //??
        HttpResponse response = httpClient.execute(request);
        headers = response.getAllHeaders();
        for (Header h : headers) {
            Map<String, List<String>> hs = fetchResult.getHeaders();
            String key = h.getName();
            List<String> val = hs.get(key);
            if (val == null)
                val = new ArrayList<String>();
            val.add(h.getValue());

            hs.put(key, val);
        }
        //URL
        fetchResult.setFetchedUrl(toFetchURL);
        String uri = request.getURI().toString();
        if (!uri.equals(toFetchURL))
            if (!URLCanonicalizer.getCanonicalURL(uri).equals(toFetchURL))
                fetchResult.setFetchedUrl(uri);

        entity = response.getEntity();
        //???
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            if (statusCode != HttpStatus.SC_NOT_FOUND) {
                Header locationHeader = response.getFirstHeader("Location");
                //301?302?URL??
                if (locationHeader != null && (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                        || statusCode == HttpStatus.SC_MOVED_TEMPORARILY))
                    fetchResult.setMovedToUrl(
                            URLCanonicalizer.getCanonicalURL(locationHeader.getValue(), toFetchURL));
            }
            //???OKURLstatusCode??
            //???
            if (this.site.getSkipStatusCode() != null && this.site.getSkipStatusCode().trim().length() > 0) {
                String[] scs = this.site.getSkipStatusCode().split(",");
                for (String code : scs) {
                    int c = CommonUtil.toInt(code);
                    //????entity
                    if (statusCode == c) {
                        assemPage(fetchResult, entity);
                        break;
                    }
                }
            }
            fetchResult.setStatusCode(statusCode);
            return fetchResult;
        }

        //??
        if (entity != null) {
            fetchResult.setStatusCode(statusCode);
            assemPage(fetchResult, entity);
            return fetchResult;
        }
    } catch (Throwable e) {
        fetchResult.setFetchedUrl(e.toString());
        fetchResult.setStatusCode(Status.INTERNAL_SERVER_ERROR.ordinal());
        return fetchResult;
    } finally {
        try {
            if (entity == null && request != null)
                request.abort();
        } catch (Exception e) {
            throw e;
        }
    }

    fetchResult.setStatusCode(Status.UNSPECIFIED_ERROR.ordinal());
    return fetchResult;
}

From source file:com.starclub.enrique.BuyActivity.java

public void updateCredit(int credit) {

    progress = new ProgressDialog(this);
    progress.setCancelable(false);//from   w  w w. j a v  a2  s .c  o m
    progress.setMessage("Updating...");

    progress.show();

    m_nCredit = credit;

    new Thread() {
        public void run() {

            HttpParams myParams = new BasicHttpParams();

            HttpConnectionParams.setConnectionTimeout(myParams, 30000);
            HttpConnectionParams.setSoTimeout(myParams, 30000);

            DefaultHttpClient hc = new DefaultHttpClient(myParams);
            ResponseHandler<String> res = new BasicResponseHandler();

            String url = Utils.getUpdateUrl();
            HttpPost postMethod = new HttpPost(url);

            String responseBody = "";
            try {
                MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

                reqEntity.addPart("cid", new StringBody("" + MyConstants.CID));
                reqEntity.addPart("token", new StringBody("" + Utils.getUserToken()));
                reqEntity.addPart("user_id", new StringBody("" + Utils.getUserID()));

                reqEntity.addPart("credit", new StringBody("" + m_nCredit));

                postMethod.setEntity(reqEntity);
                responseBody = hc.execute(postMethod, res);

                System.out.println("update result = " + responseBody);
                JSONObject result = new JSONObject(responseBody);
                if (result != null) {
                    boolean status = result.optBoolean("status");
                    if (status) {

                        m_handler.sendEmptyMessage(1);

                        return;
                    }
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
            }

            m_handler.sendEmptyMessage(-1);
        }
    }.start();
}

From source file:nl.sogeti.android.gpstracker.actions.ShareTrack.java

/**
 * POST a (GPX) file to the 0.6 API of the OpenStreetMap.org website publishing 
 * this track to the public.//ww w .  j a va 2s.co m
 * 
 * @param fileUri
 * @param contentType
 */
private void sendToOsm(Uri fileUri, Uri trackUri, String contentType) {
    String username = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_USERNAME, "");
    String password = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_PASSWORD, "");
    String visibility = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_VISIBILITY,
            "trackable");
    File gpxFile = new File(fileUri.getEncodedPath());
    String hostname = getString(R.string.osm_post_host);
    Integer port = new Integer(getString(R.string.osm_post_port));
    HttpHost targetHost = new HttpHost(hostname, port, "http");

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = null;
    String responseText = "";
    int statusCode = 0;
    Cursor metaData = null;
    String sources = null;
    try {
        metaData = this.getContentResolver().query(Uri.withAppendedPath(trackUri, "metadata"),
                new String[] { MetaData.VALUE }, MetaData.KEY + " = ? ",
                new String[] { Constants.DATASOURCES_KEY }, null);
        if (metaData.moveToFirst()) {
            sources = metaData.getString(0);
        }
        if (sources != null && sources.contains(LoggerMap.GOOGLE_PROVIDER)) {
            throw new IOException("Unable to upload track with materials derived from Google Maps.");
        }

        // The POST to the create node
        HttpPost method = new HttpPost(getString(R.string.osm_post_context));

        // Preemptive basic auth on the first request 
        method.addHeader(
                new BasicScheme().authenticate(new UsernamePasswordCredentials(username, password), method));

        // Build the multipart body with the upload data
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("file", new FileBody(gpxFile));
        entity.addPart("description", new StringBody(queryForTrackName()));
        entity.addPart("tags", new StringBody(queryForNotes()));
        entity.addPart("visibility", new StringBody(visibility));
        method.setEntity(entity);

        // Execute the POST to OpenStreetMap
        response = httpclient.execute(targetHost, method);

        // Read the response
        statusCode = response.getStatusLine().getStatusCode();
        InputStream stream = response.getEntity().getContent();
        responseText = convertStreamToString(stream);
    } catch (IOException e) {
        Log.e(TAG, "Failed to upload to " + targetHost.getHostName() + "Response: " + responseText, e);
        responseText = getString(R.string.osm_failed) + e.getLocalizedMessage();
        Toast toast = Toast.makeText(this, responseText, Toast.LENGTH_LONG);
        toast.show();
    } catch (AuthenticationException e) {
        Log.e(TAG, "Failed to upload to " + targetHost.getHostName() + "Response: " + responseText, e);
        responseText = getString(R.string.osm_failed) + e.getLocalizedMessage();
        Toast toast = Toast.makeText(this, responseText, Toast.LENGTH_LONG);
        toast.show();
    } finally {
        if (metaData != null) {
            metaData.close();
        }
    }

    if (statusCode == 200) {
        Log.i(TAG, responseText);
        CharSequence text = getString(R.string.osm_success) + responseText;
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
        toast.show();
    } else {
        Log.e(TAG, "Failed to upload to error code " + statusCode + " " + responseText);
        CharSequence text = getString(R.string.osm_failed) + responseText;
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
        toast.show();
    }
}