javatips.net counter

Java Examples for org.apache.http.entity.mime.content.StringBody

The following java examples will help you to understand the usage of org.apache.http.entity.mime.content.StringBody. These source code samples are taken from different open source projects.

Example 1
Project: Assassins-Test-master  File: KillActivity.java View source code
public void onPictureTaken(byte[] imageData, Camera c) {
    Log.v("camera info:", "got there:" + (imageData == null));
    if (imageData != null) {
        Intent mIntent = new Intent();
        AssassinsApplication app = new AssassinsApplication();
        // Bitmap bitmap=
        // BitmapFactory.decodeByteArray(imageData,0,imageData.length);
        // String imageString=Base64.encodeToString(imageData
        // ,Base64.DEFAULT);
        String url = InGameService.BASE_URL + "ingame/killrequest/";
        HttpPost httppost = new HttpPost(url);
        // Log.v("camera info:","string respresentation:"
        // +imageString.toString() );
        // List<NameValuePair> nameValuePairs = new
        // ArrayList<NameValuePair>();
        // nameValuePairs.add(new
        // BasicNameValuePair("access_token",facebook.getAccessToken()));
        // nameValuePairs.add(new
        // BasicNameValuePair("picture",imageString));
        // Log.v("taking pic, ",httppost.toString());
        // Log.v("camera info:","value pairs 0 :"
        // +nameValuePairs.get(0).toString());
        // Log.v("camera info:","value pairs 1 :"
        // +nameValuePairs.get(1).toString());
        // Log.v("camera info:","value pairs  :"
        // +nameValuePairs.toString());
        MultipartEntity mp = new MultipartEntity();
        ContentBody cb = new ByteArrayBody(imageData, "image/jpeg", "picture.jpg");
        mp.addPart("picture", cb);
        try {
            ContentBody token = new StringBody(app.getAccessToken());
            mp.addPart("access_token", token);
            httppost.setEntity(mp);
            InGameService.request(url, false, httppost);
        } catch (Exception /** UnsupportedEncodingException **/
        e) {
            e.printStackTrace();
        }
        mCamera.startPreview();
        setResult(FOTO_MODE, mIntent);
    }
}
Example 2
Project: java-client-library-master  File: RepositoryDirectoryUploadCall.java View source code
/**
     * Internal use only, to execute call use RClient.execute().
     */
public RCoreResult call() {
    RCoreResultImpl pResult = null;
    try {
        HttpPost httpPost = new HttpPost(serverUrl + API);
        super.httpUriRequest = httpPost;
        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add(new BasicNameValuePair("format", "json"));
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("file", new InputStreamBody(((InputStream) zipStream), "application/zip"));
        if (options.directory != null)
            entity.addPart("directory", new StringBody(options.directory, "text/plain", Charset.forName("UTF-8")));
        if (options.descr != null)
            entity.addPart("descr", new StringBody(options.descr, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("newversion", new StringBody(Boolean.toString(options.newversion), "text/plain", Charset.forName("UTF-8")));
        if (options.restricted != null)
            entity.addPart("restricted", new StringBody(options.restricted, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("shared", new StringBody(Boolean.toString(options.shared), "text/plain", Charset.forName("UTF-8")));
        entity.addPart("published", new StringBody(Boolean.toString(options.published), "text/plain", Charset.forName("UTF-8")));
        if (options.inputs != null)
            entity.addPart("inputs", new StringBody(options.inputs, "text/plain", Charset.forName("UTF-8")));
        if (options.outputs != null)
            entity.addPart("outputs", new StringBody(options.outputs, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("format", new StringBody("json", "text/plain", Charset.forName("UTF-8")));
        httpPost.setEntity(entity);
        // set any custom headers on the request            
        for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }
        HttpResponse response = httpClient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();
        HttpEntity responseEntity = response.getEntity();
        String markup = EntityUtils.toString(responseEntity);
        pResult = new RCoreResultImpl(response.getAllHeaders());
        pResult.parseMarkup(markup, API, statusLine.getStatusCode(), statusLine.getReasonPhrase());
    } catch (UnsupportedEncodingException ueex) {
        log.warn("RepositoryDirectoryUploadCall: unsupported encoding exception.", ueex);
    } catch (IOException ioex) {
        log.warn("RepositoryDirectoryUploadCall: io exception.", ioex);
    }
    return pResult;
}
Example 3
Project: wisdom-master  File: FileUploadTest.java View source code
@Test
public void testThatFileUpdateFailedWhenTheFileExceedTheConfiguredSize() throws InterruptedException, IOException {
    // Prepare the configuration
    ApplicationConfiguration configuration = mock(ApplicationConfiguration.class);
    when(configuration.getIntegerWithDefault(eq("vertx.http.port"), anyInt())).thenReturn(0);
    when(configuration.getIntegerWithDefault(eq("vertx.https.port"), anyInt())).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.acceptBacklog", -1)).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.receiveBufferSize", -1)).thenReturn(-1);
    when(configuration.getIntegerWithDefault("vertx.sendBufferSize", -1)).thenReturn(-1);
    when(configuration.getLongWithDefault("http.upload.disk.threshold", DiskFileUpload.MINSIZE)).thenReturn(DiskFileUpload.MINSIZE);
    // 10 bytes max
    when(configuration.getLongWithDefault("http.upload.max", -1l)).thenReturn(10l);
    when(configuration.getStringArray("wisdom.websocket.subprotocols")).thenReturn(new String[0]);
    when(configuration.getStringArray("vertx.websocket-subprotocols")).thenReturn(new String[0]);
    // Prepare the router with a controller
    Controller controller = new DefaultController() {

        @SuppressWarnings("unused")
        public Result index() {
            return ok();
        }
    };
    Router router = mock(Router.class);
    Route route = new RouteBuilder().route(HttpMethod.POST).on("/").to(controller, "index");
    when(router.getRouteFor(anyString(), anyString(), any(Request.class))).thenReturn(route);
    ContentEngine contentEngine = getMockContentEngine();
    // Configure the server.
    server = new WisdomVertxServer();
    server.accessor = new ServiceAccessor(null, configuration, router, contentEngine, executor, null, Collections.<ExceptionMapper>emptyList());
    server.configuration = configuration;
    server.vertx = vertx;
    server.start();
    VertxHttpServerTest.waitForStart(server);
    int port = server.httpPort();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost post = new HttpPost("http://localhost:" + port + "/?id=" + 1);
    ByteArrayBody body = new ByteArrayBody("this is too much...".getBytes(), "my-file.dat");
    StringBody description = new StringBody("my description", ContentType.TEXT_PLAIN);
    HttpEntity entity = MultipartEntityBuilder.create().addPart("upload", body).addPart("comment", description).build();
    post.setEntity(entity);
    CloseableHttpResponse response = httpclient.execute(post);
    // We should receive a Payload too large response (413)
    assertThat(response.getStatusLine().getStatusCode()).isEqualTo(413);
}
Example 4
Project: extdirectspring-master  File: FileUploadControllerTest.java View source code
@Test
public void testUpload() throws IOException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    InputStream is = null;
    CloseableHttpResponse response = null;
    try {
        HttpPost post = new HttpPost("http://localhost:9998/controller/router");
        is = getClass().getResourceAsStream("/UploadTestFile.txt");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        ContentBody cbFile = new InputStreamBody(is, ContentType.create("text/plain"), "UploadTestFile.txt");
        builder.addPart("fileUpload", cbFile);
        builder.addPart("extTID", new StringBody("2", ContentType.DEFAULT_TEXT));
        builder.addPart("extAction", new StringBody("fileUploadController", ContentType.DEFAULT_TEXT));
        builder.addPart("extMethod", new StringBody("uploadTest", ContentType.DEFAULT_TEXT));
        builder.addPart("extType", new StringBody("rpc", ContentType.DEFAULT_TEXT));
        builder.addPart("extUpload", new StringBody("true", ContentType.DEFAULT_TEXT));
        builder.addPart("name", new StringBody("Jimöäü", ContentType.create("text/plain", Charset.forName("UTF-8"))));
        builder.addPart("firstName", new StringBody("Ralph", ContentType.DEFAULT_TEXT));
        builder.addPart("age", new StringBody("25", ContentType.DEFAULT_TEXT));
        builder.addPart("email", new StringBody("[email protected]", ContentType.DEFAULT_TEXT));
        post.setEntity(builder.build());
        response = client.execute(post);
        HttpEntity resEntity = response.getEntity();
        assertThat(resEntity).isNotNull();
        String responseString = EntityUtils.toString(resEntity);
        String prefix = "<html><body><textarea>";
        String postfix = "</textarea></body></html>";
        assertThat(responseString).startsWith(prefix);
        assertThat(responseString).endsWith(postfix);
        String json = responseString.substring(prefix.length(), responseString.length() - postfix.length());
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> rootAsMap = mapper.readValue(json, Map.class);
        assertThat(rootAsMap).hasSize(5);
        assertThat(rootAsMap.get("method")).isEqualTo("uploadTest");
        assertThat(rootAsMap.get("type")).isEqualTo("rpc");
        assertThat(rootAsMap.get("action")).isEqualTo("fileUploadController");
        assertThat(rootAsMap.get("tid")).isEqualTo(2);
        @SuppressWarnings("unchecked") Map<String, Object> result = (Map<String, Object>) rootAsMap.get("result");
        assertThat(result).hasSize(7);
        assertThat(result.get("name")).isEqualTo("Jimöäü");
        assertThat(result.get("firstName")).isEqualTo("Ralph");
        assertThat(result.get("age")).isEqualTo(25);
        assertThat(result.get("email")).isEqualTo("[email protected]");
        assertThat(result.get("fileName")).isEqualTo("UploadTestFile.txt");
        assertThat(result.get("fileContents")).isEqualTo("contents of upload file");
        assertThat(result.get("success")).isEqualTo(Boolean.TRUE);
        EntityUtils.consume(resEntity);
    } finally {
        IOUtils.closeQuietly(response);
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(client);
    }
}
Example 5
Project: gradle-ecgine-plugin-master  File: EcgineDeployTask.java View source code
private void createEbundle(HttpClient client, EcgineExtension ext, EManifest p) throws Exception {
    HttpPost post = new HttpPost(ext.getUploadBundleUrl());
    post.addHeader("apikey", ext.getApiKey());
    post.removeHeaders("content-type");
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    File file = p.getJar();
    if (!file.exists()) {
        throw new GradleException("Run build before deploy");
    }
    builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, file.getName());
    JSONObject json = new JSONObject();
    json.put("multiple", false);
    builder.addPart("info", new StringBody(json.toString(), ContentType.APPLICATION_JSON));
    post.setEntity(builder.build());
    HttpResponse response = client.execute(post);
    HttpEntity entity = response.getEntity();
    EntityUtils.consume(entity);
}
Example 6
Project: p4-master  File: AdminConnection.java View source code
public static boolean restoreFromLTO(P4Service service, String from, String to) {
    try {
        String path = service.getURL() + "/admin/restore";
        HttpRequestBase request = new HttpPost(path);
        MultipartEntity part = new MultipartEntity();
        part.addPart("from", new StringBody(from));
        part.addPart("to", new StringBody(to));
        ((HttpPost) request).setEntity(part);
        P4HttpClient client = new P4HttpClient(service.getUserID());
        HttpEntity entity = client.executeRequest(request).getEntity();
        if (entity != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
            String line;
            if ((line = reader.readLine()) != null) {
                if (line.equals("Error")) {
                    return false;
                } else {
                    return true;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
Example 7
Project: kanqiu_letv-master  File: QHttpClient.java View source code
/**
     * Post方法传送文件和消息
     * 
     * @param url  连接的URL
     * @param queryString 请求参数串
     * @param files 上传的文件列表
     * @return 服务器返回的信息
     * @throws Exception
     */
public String httpPostWithFile(String url, String queryString, List<NameValuePair> files) throws Exception {
    String responseData = null;
    URI tmpUri = new URI(url);
    URI uri = URIUtils.createURI(tmpUri.getScheme(), tmpUri.getHost(), tmpUri.getPort(), tmpUri.getPath(), queryString, null);
    Log.i(TAG, "QHttpClient httpPostWithFile [1]  uri = " + uri.toURL());
    MultipartEntity mpEntity = new MultipartEntity();
    HttpPost httpPost = new HttpPost(uri);
    StringBody stringBody;
    FileBody fileBody;
    File targetFile;
    String filePath;
    FormBodyPart fbp;
    List<NameValuePair> queryParamList = QStrOperate.getQueryParamsList(queryString);
    for (NameValuePair queryParam : queryParamList) {
        stringBody = new StringBody(queryParam.getValue(), Charset.forName("UTF-8"));
        fbp = new FormBodyPart(queryParam.getName(), stringBody);
        mpEntity.addPart(fbp);
    //            Log.i(TAG, "------- "+queryParam.getName()+" = "+queryParam.getValue());
    }
    for (NameValuePair param : files) {
        filePath = param.getValue();
        targetFile = new File(filePath);
        fileBody = new FileBody(targetFile, "application/octet-stream");
        fbp = new FormBodyPart(param.getName(), fileBody);
        mpEntity.addPart(fbp);
    }
    //        Log.i(TAG, "---------- Entity Content Type = "+mpEntity.getContentType());
    httpPost.setEntity(mpEntity);
    try {
        HttpResponse response = httpClient.execute(httpPost);
        Log.i(TAG, "QHttpClient httpPostWithFile [2] StatusLine = " + response.getStatusLine());
        responseData = EntityUtils.toString(response.getEntity());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        httpPost.abort();
    }
    Log.i(TAG, "QHttpClient httpPostWithFile [3] responseData = " + responseData);
    return responseData;
}
Example 8
Project: astrid-master  File: ActFmInvoker.java View source code
public JSONObject postSync(String data, MultipartEntity entity, boolean changesHappened, String tok) throws IOException, ActFmServiceException {
    try {
        String timeString = DateUtilities.timeToIso8601(DateUtilities.now(), true);
        Object[] params = { "token", tok, "data", data, "time", timeString };
        if (changesHappened) {
            String gcm = Preferences.getStringValue(GCMIntentService.PREF_REGISTRATION);
            ActFmSyncThread.syncLog("Sending GCM token: " + gcm);
            if (!TextUtils.isEmpty(gcm)) {
                params = AndroidUtilities.addToArray(Object.class, params, "gcm", gcm);
                entity.addPart("gcm", new StringBody(gcm));
            }
        }
        String request = createFetchUrl("api/" + API_VERSION, "synchronize", params);
        if (SYNC_DEBUG)
            Log.e("act-fm-post", request);
        Charset chars;
        try {
            chars = Charset.forName("UTF-8");
        } catch (Exception e) {
            chars = null;
        }
        entity.addPart("token", new StringBody(tok));
        entity.addPart("data", new StringBody(data, chars));
        entity.addPart("time", new StringBody(timeString));
        String response = restClient.post(request, entity);
        JSONObject object = new JSONObject(response);
        if (SYNC_DEBUG)
            AndroidUtilities.logJSONObject("act-fm-post-response", object);
        if (object.getString("status").equals("error"))
            throw new ActFmServiceException(object.getString("message"), object);
        return object;
    } catch (JSONException e) {
        throw new IOException(e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}
Example 9
Project: sqlpower-library-master  File: ClientSideSessionUtils.java View source code
public static ProjectLocation uploadProject(SPServerInfo serviceInfo, String name, File project, UserPrompterFactory session, CookieStore cookieStore) throws URISyntaxException, ClientProtocolException, IOException, JSONException {
    HttpClient httpClient = ClientSideSessionUtils.createHttpClient(serviceInfo, cookieStore);
    try {
        MultipartEntity entity = new MultipartEntity();
        ContentBody fileBody = new FileBody(project);
        ContentBody nameBody = new StringBody(name);
        entity.addPart("file", fileBody);
        entity.addPart("name", nameBody);
        HttpPost request = new HttpPost(ClientSideSessionUtils.getServerURI(serviceInfo, "/" + ClientSideSessionUtils.REST_TAG + "/jcr", "name=" + name));
        request.setEntity(entity);
        JSONMessage message = httpClient.execute(request, new JSONResponseHandler());
        JSONObject response = new JSONObject(message.getBody());
        return new ProjectLocation(response.getString("uuid"), response.getString("name"), serviceInfo);
    } catch (AccessDeniedException e) {
        session.createUserPrompter("You do not have sufficient privileges to create a new workspace.", UserPromptType.MESSAGE, UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK").promptUser("");
        return null;
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
Example 10
Project: TestingStuff-master  File: HttpUtil.java View source code
public static String uploadFileWithParams(String url, List<String> keys, List<String> values, List<String> fileKeys, List<File> files) throws Exception {
    DefaultHttpClient mHttpClient = new DefaultHttpClient();
    Charset charSet = java.nio.charset.Charset.forName("UTF-8");
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    try {
        HttpUtil.log("strart upload file");
        HttpPost httppost = new HttpPost(url);
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        if (keys != null && values != null) {
            for (int i = 0; i < keys.size(); i++) {
                multipartEntity.addPart(keys.get(i), new StringBody(values.get(i), "text/plain", charSet));
            }
        }
        if (fileKeys != null && files != null) {
            for (int i = 0; i < fileKeys.size(); i++) {
                multipartEntity.addPart(fileKeys.get(i), new FileBody(files.get(i)));
            }
        }
        StringBuilder urlParametersBuilder = new StringBuilder();
        JsonObject jsonParams = null;
        if (keys != null && values != null) {
            if (keys.size() != values.size()) {
                throw new Exception("keys length and values length not equal.");
            }
            jsonParams = new JsonObject();
            int i;
            for (i = 0; i < keys.size(); i++) {
                if (i == 0) {
                    urlParametersBuilder.append(keys.get(i));
                    urlParametersBuilder.append("=");
                    urlParametersBuilder.append(URLEncoder.encode(values.get(i), "utf-8"));
                } else {
                    urlParametersBuilder.append("&");
                    urlParametersBuilder.append(keys.get(i));
                    urlParametersBuilder.append("=");
                    urlParametersBuilder.append(URLEncoder.encode(values.get(i), "utf-8"));
                }
                jsonParams.addProperty(keys.get(i), values.get(i));
            }
        }
        httppost.setEntity(multipartEntity);
        httppost.setParams(params);
        HttpUtil.log("strart...");
        LogController.log("httpPOst>>>>>>" + httppost);
        HttpResponse httpResponse = mHttpClient.execute(httppost);
        LogController.log("httpPost>>>" + httppost);
        String result = null;
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        HttpUtil.log("file upload statusCode >>> " + statusCode);
        if (statusCode == HttpURLConnection.HTTP_OK) {
            result = EntityUtils.toString(httpResponse.getEntity());
        } else {
            throw new Exception("Http Status Code not 200.");
        }
        HttpUtil.log("file upload result >>> " + result);
        HttpUtil.log("file upload call finished");
        return result;
    } catch (Exception e) {
        HttpUtil.log("upload file exception");
        e.printStackTrace();
        throw e;
    }
}
Example 11
Project: Lyric-Music-Player-master  File: ActivityLyric.java View source code
public void uploadTo(String name, String artist, File file, String type) throws Exception {
    String url = "";
    if (type == "music") {
        url = "http://10.0.2.2:8000/upload/music";
    } else {
        url = "http://10.0.2.2:8000/upload/lyric";
    }
    Log.d("salam", url);
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    MultipartEntity mpEntity = new MultipartEntity();
    //Path of the file to be uploaded
    ContentBody cbFile = new FileBody(file, "text/plain");
    //Add the data to the multipart entity
    mpEntity.addPart(type, cbFile);
    mpEntity.addPart("name", new StringBody(name, Charset.forName("UTF-8")));
    mpEntity.addPart("artist", new StringBody(artist, Charset.forName("UTF-8")));
    post.setEntity(mpEntity);
    //Execute the post request
    HttpResponse response1 = client.execute(post);
    //Get the response from the server
    HttpEntity resEntity = response1.getEntity();
    String Response = EntityUtils.toString(resEntity);
    Log.d("Response:", Response);
    //Generate the array from the response
    JSONArray jsonarray = new JSONArray("[" + Response + "]");
    JSONObject jsonobject = jsonarray.getJSONObject(0);
    //Get the result variables from response 
    String result = (jsonobject.getString("result"));
    String msg = (jsonobject.getString("msg"));
    //Close the connection
    client.getConnectionManager().shutdown();
}
Example 12
Project: WebQQCore-master  File: ApacheHttpService.java View source code
@Override
public Future<QQHttpResponse> executeHttpRequest(QQHttpRequest request, QQHttpListener listener) throws QQException {
    try {
        URI uri = URI.create(request.getUrl());
        if (request.getMethod().equals("POST")) {
            HttpPost httppost = new HttpPost(uri);
            HttpHost httphost = URIUtils.extractHost(uri);
            Builder requestConfigBuilder = RequestConfig.copy(RequestConfig.DEFAULT);
            if (request.getReadTimeout() > 0) {
                requestConfigBuilder.setSocketTimeout(request.getReadTimeout());
            }
            if (request.getConnectTimeout() > 0) {
                requestConfigBuilder.setConnectTimeout(request.getConnectTimeout());
            }
            httppost.setConfig(requestConfigBuilder.build());
            if (request.getFileMap().size() > 0) {
                MultipartEntity entity = new MultipartEntity();
                String charset = request.getCharset();
                Map<String, String> postMap = request.getPostMap();
                for (String key : postMap.keySet()) {
                    String value = postMap.get(key);
                    value = value == null ? "" : value;
                    entity.addPart(key, new StringBody(value, Charset.forName(charset)));
                }
                Map<String, File> fileMap = request.getFileMap();
                for (String key : fileMap.keySet()) {
                    File value = fileMap.get(key);
                    entity.addPart(new FormBodyPart(key, new FileBody(value, getMimeType(value))));
                }
                httppost.setEntity(entity);
            } else if (request.getPostMap().size() > 0) {
                List<NameValuePair> list = new ArrayList<NameValuePair>();
                Map<String, String> postMap = request.getPostMap();
                for (String key : postMap.keySet()) {
                    String value = postMap.get(key);
                    value = value == null ? "" : value;
                    list.add(new BasicNameValuePair(key, value));
                }
                httppost.setEntity(new UrlEncodedFormEntity(list, request.getCharset()));
            }
            Map<String, String> headerMap = request.getHeaderMap();
            for (String key : headerMap.keySet()) {
                httppost.addHeader(key, headerMap.get(key));
            }
            QQHttpPostRequestProducer producer = new QQHttpPostRequestProducer(httphost, httppost, listener);
            QQHttpResponseConsumer consumer = new QQHttpResponseConsumer(request, listener, cookieJar);
            QQHttpResponseCallback callback = new QQHttpResponseCallback(listener);
            Future<QQHttpResponse> future = asyncHttpClient.execute(producer, consumer, callback);
            return new ProxyFuture(future, consumer, producer);
        } else if (request.getMethod().equals("GET")) {
            HttpGet httpget = new HttpGet(uri);
            HttpHost httphost = URIUtils.extractHost(uri);
            Map<String, String> headerMap = request.getHeaderMap();
            for (String key : headerMap.keySet()) {
                httpget.addHeader(key, headerMap.get(key));
            }
            Builder requestConfigBuilder = RequestConfig.copy(RequestConfig.DEFAULT);
            if (request.getReadTimeout() > 0) {
                requestConfigBuilder.setSocketTimeout(request.getReadTimeout());
            }
            if (request.getConnectTimeout() > 0) {
                requestConfigBuilder.setConnectTimeout(request.getConnectTimeout());
            }
            httpget.setConfig(requestConfigBuilder.build());
            return asyncHttpClient.execute(new QQHttpGetRequestProducer(httphost, httpget), new QQHttpResponseConsumer(request, listener, cookieJar), new QQHttpResponseCallback(listener));
        } else {
            throw new QQException(QQErrorCode.IO_ERROR, "not support http method:" + request.getMethod());
        }
    } catch (IOException e) {
        throw new QQException(QQErrorCode.IO_ERROR);
    }
}
Example 13
Project: tmdm-studio-se-master  File: HttpClientUtil.java View source code
private static HttpUriRequest createUploadRequest(String URL, String userName, String localFilename, String filename, String imageCatalog, HashMap<String, String> picturePathMap) {
    HttpPost request = new HttpPost(URL);
    MultipartEntity entity = new MultipartEntity();
    if (!Messages.Util_24.equalsIgnoreCase(localFilename)) {
        File file = new File(localFilename);
        if (file.exists()) {
            //$NON-NLS-1$
            entity.addPart("imageFile", new FileBody(file));
        }
    }
    if (imageCatalog != null) {
        //$NON-NLS-1$
        entity.addPart("catalogName", StringBody.create(imageCatalog, STRING_CONTENT_TYPE, null));
    }
    if (filename != null) {
        int pos = filename.lastIndexOf('.');
        if (pos != -1) {
            filename = filename.substring(0, pos);
        }
        //$NON-NLS-1$
        entity.addPart("fileName", StringBody.create(filename, STRING_CONTENT_TYPE, null));
    }
    request.setEntity(entity);
    addStudioToken(request, userName);
    return request;
}
Example 14
Project: MUtils-master  File: NetClient.java View source code
/**
     * Convert object to HttpEntity
     */
public static HttpEntity convertToEntity(Object object) {
    if (object == null) {
        return null;
    }
    if (object instanceof String) {
        try {
            return new StringEntity((String) object, "UTF-8");
        } catch (Exception e) {
            return null;
        }
    } else {
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        if (object instanceof Map) {
            for (Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) {
                Object key = entry.getKey();
                Object value = entry.getValue();
                if (key == null || value == null) {
                    continue;
                }
                if (value instanceof File) {
                    entity.addPart(key.toString(), new FileBody((File) value));
                } else {
                    try {
                        entity.addPart(key.toString(), new StringBody(JsonUtil.toString(value), Charset.forName("UTF-8")));
                    } catch (Exception e) {
                    }
                }
            }
        } else {
            for (BeanField field : BeanField.getFields(object.getClass())) {
                try {
                    Object value = field.get(object);
                    if (value == null) {
                        continue;
                    }
                    if (value instanceof File) {
                        entity.addPart(field.getName(), new FileBody((File) value));
                    } else {
                        entity.addPart(field.getName(), new StringBody(JsonUtil.toString(value), Charset.forName("UTF-8")));
                    }
                } catch (Exception e) {
                }
            }
        }
        return entity;
    }
}
Example 15
Project: lucene-solr-master  File: HttpSolrClient.java View source code
protected HttpRequestBase createMethod(final SolrRequest request, String collection) throws IOException, SolrServerException {
    SolrParams params = request.getParams();
    Collection<ContentStream> streams = requestWriter.getContentStreams(request);
    String path = requestWriter.getPath(request);
    if (path == null || !path.startsWith("/")) {
        path = DEFAULT_PATH;
    }
    ResponseParser parser = request.getResponseParser();
    if (parser == null) {
        parser = this.parser;
    }
    // The parser 'wt=' and 'version=' params are used instead of the original
    // params
    ModifiableSolrParams wparams = new ModifiableSolrParams(params);
    if (parser != null) {
        wparams.set(CommonParams.WT, parser.getWriterType());
        wparams.set(CommonParams.VERSION, parser.getVersion());
    }
    if (invariantParams != null) {
        wparams.add(invariantParams);
    }
    String basePath = baseUrl;
    if (collection != null)
        basePath += "/" + collection;
    if (SolrRequest.METHOD.GET == request.getMethod()) {
        if (streams != null) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
        }
        return new HttpGet(basePath + path + wparams.toQueryString());
    }
    if (SolrRequest.METHOD.POST == request.getMethod() || SolrRequest.METHOD.PUT == request.getMethod()) {
        String url = basePath + path;
        boolean hasNullStreamName = false;
        if (streams != null) {
            for (ContentStream cs : streams) {
                if (cs.getName() == null) {
                    hasNullStreamName = true;
                    break;
                }
            }
        }
        boolean isMultipart = ((this.useMultiPartPost && SolrRequest.METHOD.POST == request.getMethod()) || (streams != null && streams.size() > 1)) && !hasNullStreamName;
        LinkedList<NameValuePair> postOrPutParams = new LinkedList<>();
        if (streams == null || isMultipart) {
            // send server list and request list as query string params
            ModifiableSolrParams queryParams = calculateQueryParams(this.queryParams, wparams);
            queryParams.add(calculateQueryParams(request.getQueryParams(), wparams));
            String fullQueryUrl = url + queryParams.toQueryString();
            HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == request.getMethod() ? new HttpPost(fullQueryUrl) : new HttpPut(fullQueryUrl);
            if (!isMultipart) {
                postOrPut.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            }
            List<FormBodyPart> parts = new LinkedList<>();
            Iterator<String> iter = wparams.getParameterNamesIterator();
            while (iter.hasNext()) {
                String p = iter.next();
                String[] vals = wparams.getParams(p);
                if (vals != null) {
                    for (String v : vals) {
                        if (isMultipart) {
                            parts.add(new FormBodyPart(p, new StringBody(v, StandardCharsets.UTF_8)));
                        } else {
                            postOrPutParams.add(new BasicNameValuePair(p, v));
                        }
                    }
                }
            }
            // TODO: remove deprecated - first simple attempt failed, see [email protected] MultipartEntityBuilder}
            if (isMultipart && streams != null) {
                for (ContentStream content : streams) {
                    String contentType = content.getContentType();
                    if (contentType == null) {
                        // default
                        contentType = BinaryResponseParser.BINARY_CONTENT_TYPE;
                    }
                    String name = content.getName();
                    if (name == null) {
                        name = "";
                    }
                    parts.add(new FormBodyPart(name, new InputStreamBody(content.getStream(), contentType, content.getName())));
                }
            }
            if (parts.size() > 0) {
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);
                for (FormBodyPart p : parts) {
                    entity.addPart(p);
                }
                postOrPut.setEntity(entity);
            } else {
                //not using multipart
                postOrPut.setEntity(new UrlEncodedFormEntity(postOrPutParams, StandardCharsets.UTF_8));
            }
            return postOrPut;
        } else // It is has one stream, it is the post body, put the params in the URL
        {
            String fullQueryUrl = url + wparams.toQueryString();
            HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == request.getMethod() ? new HttpPost(fullQueryUrl) : new HttpPut(fullQueryUrl);
            // Single stream as body
            // Using a loop just to get the first one
            final ContentStream[] contentStream = new ContentStream[1];
            for (ContentStream content : streams) {
                contentStream[0] = content;
                break;
            }
            if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
                Long size = contentStream[0].getSize();
                postOrPut.setEntity(new InputStreamEntity(contentStream[0].getStream(), size == null ? -1 : size) {

                    @Override
                    public Header getContentType() {
                        return new BasicHeader("Content-Type", contentStream[0].getContentType());
                    }

                    @Override
                    public boolean isRepeatable() {
                        return false;
                    }
                });
            } else {
                Long size = contentStream[0].getSize();
                postOrPut.setEntity(new InputStreamEntity(contentStream[0].getStream(), size == null ? -1 : size) {

                    @Override
                    public Header getContentType() {
                        return new BasicHeader("Content-Type", contentStream[0].getContentType());
                    }

                    @Override
                    public boolean isRepeatable() {
                        return false;
                    }
                });
            }
            return postOrPut;
        }
    }
    throw new SolrServerException("Unsupported method: " + request.getMethod());
}
Example 16
Project: Protocoder-master  File: PNetwork.java View source code
@ProtocoderScript
@APIMethod(description = "Simple http post request. It needs an object to be sent. If an element of the object contains the key file then it will try to upload the resource indicated in the value as Uri ", example = "")
@APIParam(params = { "url", "params", "function(responseString)" })
public void httpPost(String url, Object object, final HttpPostCB callbackfn) {
    final HttpClient httpClient = new DefaultHttpClient();
    final HttpContext localContext = new BasicHttpContext();
    final HttpPost httpPost = new HttpPost(url);
    Gson g = new Gson();
    JsonArray q = g.toJsonTree(object).getAsJsonArray();
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (int i = 0; i < q.size(); i++) {
        Set<Entry<String, JsonElement>> set = q.get(i).getAsJsonObject().entrySet();
        // go through elements
        String name = "";
        String content = "";
        String type = "";
        for (Object element : set) {
            Entry<String, JsonElement> entry = (Entry<String, JsonElement>) element;
            if (entry.getKey().equals("name")) {
                name = entry.getValue().getAsString();
            } else if (entry.getKey().equals("content")) {
                content = entry.getValue().getAsString();
            } else if (entry.getKey().equals("type")) {
                type = entry.getValue().getAsString();
            }
        }
        // create the multipart
        if (type.contains("file")) {
            File f = new File(ProjectManager.getInstance().getCurrentProject().getStoragePath() + "/" + content);
            ContentBody cbFile = new FileBody(f);
            entity.addPart(name, cbFile);
        } else if (type.contains("text")) {
            // Normal string data
            try {
                entity.addPart(name, new StringBody(content));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }
    // send
    httpPost.setEntity(entity);
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                HttpResponse response = httpClient.execute(httpPost, localContext);
                callbackfn.event(response.getStatusLine().toString());
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
}
Example 17
Project: ohmagePhone-master  File: OhmageApi.java View source code
public UploadResponse surveyUpload(String serverUrl, String username, String hashedPassword, String client, String campaignUrn, String campaignCreationTimestamp, String responseJson, ArrayList<MediaPart> media) {
    final boolean GZIP = false;
    String url = serverUrl + SURVEY_UPLOAD_PATH;
    try {
        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart("campaign_urn", new StringBody(campaignUrn));
        multipartEntity.addPart("campaign_creation_timestamp", new StringBody(campaignCreationTimestamp));
        multipartEntity.addPart("user", new StringBody(username));
        multipartEntity.addPart("password", new StringBody(hashedPassword));
        multipartEntity.addPart("client", new StringBody(client));
        multipartEntity.addPart("surveys", new StringBody(responseJson));
        for (MediaPart m : media) {
            multipartEntity.addPart(m.getName(), m.getFileBody());
        }
        return parseUploadResponse(url, doHttpPost(url, multipartEntity, GZIP));
    } catch (IOException e) {
        Log.e(TAG, "IOException while creating http entity", e);
        return new UploadResponse(Result.INTERNAL_ERROR, null);
    }
}