Search in sources :

Example 26 with MultipartEntity

use of org.apache.http.entity.mime.MultipartEntity in project stanbol by apache.

the class ReasonersOfflineTest method testPostMultipartConsistency409.

@Test
public void testPostMultipartConsistency409() throws Exception {
    FileBody bin = new FileBody(new File(URI.create(inconsistentFileName)));
    MultipartEntity incMultiPart = new MultipartEntity();
    incMultiPart.addPart(fileParam, bin);
    String[] services = { "/owl", "/owlmini" };
    // Not consistent
    for (String s : services) {
        executor.execute(buildMultipartRequest("/reasoners" + s + "/check", incMultiPart)).assertStatus(409);
    }
}
Also used : FileBody(org.apache.http.entity.mime.content.FileBody) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) File(java.io.File) Test(org.junit.Test)

Example 27 with MultipartEntity

use of org.apache.http.entity.mime.MultipartEntity in project AndroidSDK-RecipeBook by gabu.

the class Recipe095 method uploadForTumblr.

// 指定されたUriの写真をTumblrにアップロードします。
private void uploadForTumblr(Uri uri) {
    // HTTPクライアントを作って
    HttpClient client = new DefaultHttpClient();
    // POST先のURLを指定してPOSTオブジェクトを作って
    HttpPost post = new HttpPost("http://www.tumblr.com/api/write");
    // パラメータを作って
    MultipartEntity entity = new MultipartEntity();
    try {
        // Thumblrに登録したメールアドレス
        entity.addPart("email", new StringBody("hoge@example.com"));
        // Thumblrに登録したパスワード
        entity.addPart("password", new StringBody("1234"));
        // 投稿する種類。今回は写真なのでphoto
        entity.addPart("type", new StringBody("photo"));
        // 写真データ
        entity.addPart("data", new InputStreamBody(getContentResolver().openInputStream(uri), "filename"));
        // POSTオブジェクトにパラメータをセット
        post.setEntity(entity);
        // POSTリクエストを実行
        client.execute(post);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) FileNotFoundException(java.io.FileNotFoundException) InputStreamBody(org.apache.http.entity.mime.content.InputStreamBody) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 28 with MultipartEntity

use of org.apache.http.entity.mime.MultipartEntity in project Talon-for-Twitter by klinker24.

the class TwitterMultipleImageHelper method uploadPics.

public boolean uploadPics(File[] pics, String text, Twitter twitter) {
    JSONObject jsonresponse = new JSONObject();
    final String ids_string = getMediaIds(pics, twitter);
    if (ids_string == null) {
        return false;
    }
    try {
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();
        // generate authorization header
        String get_or_post = "POST";
        String oauth_signature_method = "HMAC-SHA1";
        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        // any relatively random alphanumeric string will work here
        String oauth_nonce = uuid_string;
        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        // get current time in milliseconds
        long ts = tempcal.getTimeInMillis();
        // then divide by 1000 to get seconds
        String oauth_timestamp = (new Long(ts / 1000)).toString();
        // the parameter string must be in alphabetical order, "text" parameter added at end
        String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";
        System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string);
        String twitter_endpoint = "https://api.twitter.com/1.1/statuses/update.json";
        String twitter_endpoint_host = "api.twitter.com";
        String twitter_endpoint_path = "/1.1/statuses/update.json";
        String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string);
        String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));
        String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors
        new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors
        new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });
        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpContext context = new BasicHttpContext(null);
        HttpHost host = new HttpHost(twitter_endpoint_host, 443);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
        try {
            try {
                SSLContext sslcontext = SSLContext.getInstance("TLS");
                sslcontext.init(null, null, null);
                SSLSocketFactory ssf = sslcontext.getSocketFactory();
                Socket socket = ssf.createSocket();
                socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
                conn.bind(socket, params);
                BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST", twitter_endpoint_path);
                MultipartEntity reqEntity = new MultipartEntity();
                reqEntity.addPart("media_ids", new StringBody(ids_string));
                reqEntity.addPart("status", new StringBody(text));
                reqEntity.addPart("trim_user", new StringBody("1"));
                request2.setEntity(reqEntity);
                request2.setParams(params);
                request2.addHeader("Authorization", authorization_header_string);
                httpexecutor.preProcess(request2, httpproc, context);
                HttpResponse response2 = httpexecutor.execute(request2, conn, context);
                response2.setParams(params);
                httpexecutor.postProcess(response2, httpproc, context);
                String responseBody = EntityUtils.toString(response2.getEntity());
                System.out.println("response=" + responseBody);
                // error checking here. Otherwise, status should be updated.
                jsonresponse = new JSONObject(responseBody);
                conn.close();
            } catch (HttpException he) {
                System.out.println(he.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus HttpException message=" + he.getMessage());
            } catch (NoSuchAlgorithmException nsae) {
                System.out.println(nsae.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus NoSuchAlgorithmException message=" + nsae.getMessage());
            } catch (KeyManagementException kme) {
                System.out.println(kme.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus KeyManagementException message=" + kme.getMessage());
            } finally {
                conn.close();
            }
        } catch (JSONException jsone) {
            jsone.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    } catch (Exception e) {
    }
    return true;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) AccessToken(twitter4j.auth.AccessToken) BasicHttpParams(org.apache.http.params.BasicHttpParams) SyncBasicHttpParams(org.apache.http.params.SyncBasicHttpParams) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest) Calendar(java.util.Calendar) JSONException(org.json.JSONException) DefaultHttpClientConnection(org.apache.http.impl.DefaultHttpClientConnection) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) JSONException(org.json.JSONException) GeneralSecurityException(java.security.GeneralSecurityException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TwitterException(twitter4j.TwitterException) IOException(java.io.IOException) BasicHttpParams(org.apache.http.params.BasicHttpParams) SyncBasicHttpParams(org.apache.http.params.SyncBasicHttpParams) HttpParams(org.apache.http.params.HttpParams) JSONObject(org.json.JSONObject) StringBody(org.apache.http.entity.mime.content.StringBody) Socket(java.net.Socket)

Example 29 with MultipartEntity

use of org.apache.http.entity.mime.MultipartEntity in project mobile-android by photo.

the class ApiBase method createFileOnlyMultipartEntity.

private HttpEntity createFileOnlyMultipartEntity(ApiRequest request) throws UnsupportedEncodingException {
    MultipartEntity entity = new MultipartEntity();
    for (Parameter<?> parameter : request.getParametersMime()) {
        if (parameter.getValue() instanceof File) {
            File file = (File) parameter.getValue();
            entity.addPart(parameter.getName(), new FileBody(file));
        }
    }
    return entity;
}
Also used : FileBody(org.apache.http.entity.mime.content.FileBody) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) File(java.io.File)

Example 30 with MultipartEntity

use of org.apache.http.entity.mime.MultipartEntity in project RESTdoclet by IG-Group.

the class FileUploader method upload.

/**
    * Method to upload (post) a jar to the RESTDoclet web app at the given url,
    * and store it on the server in the given location.
    * 
    * @param url the RESTDoclet web app url to which to post
    * @param deployDir the RESTDoclet web app directory where the jar will be
    *           extracted
    * @param file the jar to be uploaded
    */
public static void upload(String url, String deployDir, File file) {
    LOG.debug("Uploading " + file.getName() + " to " + url);
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        FileBody bin = new FileBody(file);
        reqEntity.addPart("attachment_field", bin);
        httppost.setEntity(reqEntity);
        httppost.setHeader(RESTDOCLET_DEPLOY, deployDir);
        HttpResponse response = httpclient.execute(httppost);
        if (response.getStatusLine().getStatusCode() != 200) {
            LOG.error("Failed to upload " + file.getName() + " to " + url + " : " + response.getStatusLine());
        }
    } catch (Exception e) {
        LOG.error("Failed to upload " + file.getName() + " to " + url, e);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Aggregations

MultipartEntity (org.apache.http.entity.mime.MultipartEntity)62 HttpPost (org.apache.http.client.methods.HttpPost)41 StringBody (org.apache.http.entity.mime.content.StringBody)40 FileBody (org.apache.http.entity.mime.content.FileBody)37 File (java.io.File)31 HttpResponse (org.apache.http.HttpResponse)28 Test (org.junit.Test)24 TestHttpClient (io.undertow.testutils.TestHttpClient)13 IOException (java.io.IOException)13 InputStreamBody (org.apache.http.entity.mime.content.InputStreamBody)7 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)7 JSONObject (org.json.JSONObject)7 HashMap (java.util.HashMap)5 Map (java.util.Map)5 HttpEntity (org.apache.http.HttpEntity)5 ByteArrayBody (org.apache.http.entity.mime.content.ByteArrayBody)5 RequestBuilder (org.apache.sling.testing.tools.http.RequestBuilder)5 JSONException (org.json.JSONException)5 BlockingHandler (io.undertow.server.handlers.BlockingHandler)4 InputStream (java.io.InputStream)4