use of org.apache.http.entity.mime.content.FileBody in project Talon-for-Twitter by klinker24.
the class TwitterMultipleImageHelper method getMediaIds.
public String getMediaIds(File[] pics, Twitter twitter) {
JSONObject jsonresponse = new JSONObject();
String ids = "";
for (int i = 0; i < pics.length; i++) {
File file = pics[i];
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://upload.twitter.com/1.1/media/upload.json";
String twitter_endpoint_host = "upload.twitter.com";
String twitter_endpoint_path = "/1.1/media/upload.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);
// need to add status parameter to this POST
MultipartEntity reqEntity = new MultipartEntity();
FileBody sb_image = new FileBody(file);
reqEntity.addPart("media", sb_image);
request2.setEntity(reqEntity);
request2.setParams(params);
request2.addHeader("Authorization", authorization_header_string);
System.out.println("Twitter.updateStatusWithMedia(): Entity, params and header added to request. Preprocessing and executing...");
httpexecutor.preProcess(request2, httpproc, context);
HttpResponse response2 = httpexecutor.execute(request2, conn, context);
System.out.println("Twitter.updateStatusWithMedia(): ... done. Postprocessing...");
response2.setParams(params);
httpexecutor.postProcess(response2, httpproc, context);
String responseBody = EntityUtils.toString(response2.getEntity());
System.out.println("Twitter.updateStatusWithMedia(): done. response=" + responseBody);
// error checking here. Otherwise, status should be updated.
jsonresponse = new JSONObject(responseBody);
if (jsonresponse.has("errors")) {
JSONObject temp_jo = new JSONObject();
temp_jo.put("response_status", "error");
temp_jo.put("message", jsonresponse.getJSONArray("errors").getJSONObject(0).getString("message"));
temp_jo.put("twitter_code", jsonresponse.getJSONArray("errors").getJSONObject(0).getInt("code"));
jsonresponse = temp_jo;
}
// add it to the media_ids string
ids += jsonresponse.getString("media_id_string");
if (i != pics.length - 1) {
ids += ",";
}
conn.close();
} catch (HttpException he) {
System.out.println(he.getMessage());
jsonresponse.put("response_status", "error");
jsonresponse.put("message", "updateStatusWithMedia HttpException message=" + he.getMessage());
return null;
} catch (NoSuchAlgorithmException nsae) {
System.out.println(nsae.getMessage());
jsonresponse.put("response_status", "error");
jsonresponse.put("message", "updateStatusWithMedia NoSuchAlgorithmException message=" + nsae.getMessage());
return null;
} catch (KeyManagementException kme) {
System.out.println(kme.getMessage());
jsonresponse.put("response_status", "error");
jsonresponse.put("message", "updateStatusWithMedia KeyManagementException message=" + kme.getMessage());
return null;
} finally {
conn.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
jsonresponse.put("response_status", "error");
jsonresponse.put("message", "updateStatusWithMedia IOException message=" + ioe.getMessage());
return null;
}
} catch (Exception e) {
return null;
}
}
return ids;
}
use of org.apache.http.entity.mime.content.FileBody in project nanohttpd by NanoHttpd.
the class TestNanoFileUpLoad method executeUpload.
private void executeUpload(CloseableHttpClient httpclient, String textFileName, HttpPost post) throws IOException, ClientProtocolException {
FileBody fileBody = new FileBody(new File(textFileName), ContentType.DEFAULT_BINARY);
StringBody stringBody1 = new StringBody("Message 1", ContentType.MULTIPART_FORM_DATA);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("upfile", fileBody);
builder.addPart("text1", stringBody1);
HttpEntity entity = builder.build();
//
post.setEntity(entity);
HttpResponse response = httpclient.execute(post);
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
}
use of org.apache.http.entity.mime.content.FileBody in project FBReaderJ by geometer.
the class ZLNetworkManager method perform.
void perform(ZLNetworkRequest request, BearerAuthenticator authenticator, int socketTimeout, int connectionTimeout) throws ZLNetworkException {
boolean success = false;
DefaultHttpClient httpClient = null;
HttpEntity entity = null;
try {
final HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, CookieStore);
request.doBefore();
final HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, socketTimeout);
HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
httpClient = new DefaultHttpClient(params) {
protected AuthenticationHandler createTargetAuthenticationHandler() {
final AuthenticationHandler base = super.createTargetAuthenticationHandler();
return new AuthenticationHandler() {
public Map<String, Header> getChallenges(HttpResponse response, HttpContext context) throws MalformedChallengeException {
return base.getChallenges(response, context);
}
public boolean isAuthenticationRequested(HttpResponse response, HttpContext context) {
return base.isAuthenticationRequested(response, context);
}
public AuthScheme selectScheme(Map<String, Header> challenges, HttpResponse response, HttpContext context) throws AuthenticationException {
try {
return base.selectScheme(challenges, response, context);
} catch (AuthenticationException e) {
final Header bearerHeader = challenges.get("bearer");
if (bearerHeader != null) {
String realm = null;
for (HeaderElement elt : bearerHeader.getElements()) {
final String name = elt.getName();
if (name == null) {
continue;
}
if ("realm".equals(name) || name.endsWith(" realm")) {
realm = elt.getValue();
break;
}
}
throw new BearerAuthenticationException(realm, response.getEntity());
}
throw e;
}
}
};
}
};
final HttpRequestBase httpRequest;
if (request instanceof ZLNetworkRequest.Get) {
httpRequest = new HttpGet(request.URL);
} else if (request instanceof ZLNetworkRequest.PostWithBody) {
httpRequest = new HttpPost(request.URL);
((HttpPost) httpRequest).setEntity(new StringEntity(((ZLNetworkRequest.PostWithBody) request).Body, "utf-8"));
/*
httpConnection.setRequestProperty(
"Content-Length",
Integer.toString(request.Body.getBytes().length)
);
*/
} else if (request instanceof ZLNetworkRequest.PostWithMap) {
final Map<String, String> parameters = ((ZLNetworkRequest.PostWithMap) request).PostParameters;
httpRequest = new HttpPost(request.URL);
final List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(parameters.size());
for (Map.Entry<String, String> entry : parameters.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(list, "utf-8"));
} else if (request instanceof ZLNetworkRequest.FileUpload) {
final ZLNetworkRequest.FileUpload uploadRequest = (ZLNetworkRequest.FileUpload) request;
final File file = ((ZLNetworkRequest.FileUpload) request).File;
httpRequest = new HttpPost(request.URL);
final MultipartEntity data = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("utf-8"));
data.addPart("file", new FileBody(uploadRequest.File));
((HttpPost) httpRequest).setEntity(data);
} else {
throw new ZLNetworkException("Unknown request type");
}
httpRequest.setHeader("User-Agent", ZLNetworkUtil.getUserAgent());
if (!request.isQuiet()) {
httpRequest.setHeader("X-Accept-Auto-Login", "True");
}
httpRequest.setHeader("Accept-Encoding", "gzip");
httpRequest.setHeader("Accept-Language", ZLResource.getLanguage());
for (Map.Entry<String, String> header : request.Headers.entrySet()) {
httpRequest.setHeader(header.getKey(), header.getValue());
}
httpClient.setCredentialsProvider(new MyCredentialsProvider(httpRequest, request.isQuiet()));
final HttpResponse response = execute(httpClient, httpRequest, httpContext, authenticator);
entity = response.getEntity();
if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
final AuthState state = (AuthState) httpContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
if (state != null) {
final AuthScopeKey key = new AuthScopeKey(state.getAuthScope());
if (myCredentialsCreator.removeCredentials(key)) {
entity = null;
}
}
}
final int responseCode = response.getStatusLine().getStatusCode();
InputStream stream = null;
if (entity != null && (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_PARTIAL)) {
stream = entity.getContent();
}
if (stream != null) {
try {
final Header encoding = entity.getContentEncoding();
if (encoding != null && "gzip".equalsIgnoreCase(encoding.getValue())) {
stream = new GZIPInputStream(stream);
}
request.handleStream(stream, (int) entity.getContentLength());
} finally {
stream.close();
}
success = true;
} else {
if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
throw new ZLNetworkAuthenticationException();
} else {
throw new ZLNetworkException(response.getStatusLine().toString());
}
}
} catch (ZLNetworkException e) {
throw e;
} catch (IOException e) {
e.printStackTrace();
final String code;
if (e instanceof UnknownHostException) {
code = ZLNetworkException.ERROR_RESOLVE_HOST;
} else {
code = ZLNetworkException.ERROR_CONNECT_TO_HOST;
}
throw ZLNetworkException.forCode(code, ZLNetworkUtil.hostFromUrl(request.URL), e);
} catch (Exception e) {
e.printStackTrace();
throw new ZLNetworkException(e.getMessage(), e);
} finally {
request.doAfter(success);
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
}
if (entity != null) {
try {
entity.consumeContent();
} catch (IOException e) {
}
}
}
}
use of org.apache.http.entity.mime.content.FileBody in project project-build-plugin by axonivy.
the class HttpDeployer method getRequestData.
private HttpEntity getRequestData(File resolvedOptionsFile) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("fileToDeploy", new FileBody(deployFile));
if (resolvedOptionsFile != null) {
builder.addPart("deploymentOptions", new FileBody(resolvedOptionsFile, ContentType.TEXT_PLAIN));
}
return builder.build();
}
use of org.apache.http.entity.mime.content.FileBody in project carbon-apimgt by wso2.
the class WSO2APIPublisher method importAPIToExternalStore.
/**
* Imports an API to external Store by calling Admin import API REST service. If overwrite is true, then the API
* which is already published in external store will be updated.
*
* @param apiArchive API zipped file
* @param store external store to import
* @param overwrite whether to import or update APII
* @return HTTP Response whether import is successful or not
* @throws APIManagementException If an error occurs while importing API.
*/
private CloseableHttpResponse importAPIToExternalStore(File apiArchive, APIStore store, Boolean overwrite) throws APIManagementException {
MultipartEntityBuilder multipartEntityBuilder;
String storeEndpoint = null;
CloseableHttpClient httpclient;
URIBuilder uriBuilder;
HttpPost httppost;
CloseableHttpResponse httpResponse;
try {
multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.addPart(APIConstants.RestApiConstants.IMPORT_API_ARCHIVE_FILE, new FileBody(apiArchive));
// Get Publisher REST API apis/import endpoint from given store endpoint
storeEndpoint = getPublisherRESTURLFromStoreURL(store.getEndpoint()) + APIConstants.RestApiConstants.REST_API_PUBLISHER_API_IMPORT_RESOURCE;
httpclient = getHttpClient(storeEndpoint);
uriBuilder = new URIBuilder(storeEndpoint);
// Add preserveProvider query parameter false
uriBuilder.addParameter(APIConstants.RestApiConstants.IMPORT_API_PRESERVE_PROVIDER, Boolean.FALSE.toString());
uriBuilder.addParameter(APIConstants.RestApiConstants.IMPORT_API_OVERWRITE, overwrite.toString());
httppost = new HttpPost(uriBuilder.build());
httppost.setEntity(multipartEntityBuilder.build());
// Set Authorization Header of external store admin
httppost.setHeader(HttpHeaders.AUTHORIZATION, getBasicAuthorizationHeader(store));
if (log.isDebugEnabled()) {
log.debug("Invoking Admin REST API of external store: " + storeEndpoint + " to import API archive: " + apiArchive.getName());
}
// Call import API of external store
httpResponse = httpclient.execute(httppost);
} catch (URISyntaxException e) {
String errorMessage = "Error while building URI for store endpoint: " + storeEndpoint;
log.error(errorMessage, e);
throw new APIManagementException(errorMessage, e);
} catch (IOException e) {
String errorMessage = "Error while importing to external Store: " + storeEndpoint;
log.error(errorMessage, e);
throw new APIManagementException(errorMessage, e);
} finally {
FileUtils.deleteQuietly(apiArchive);
}
return httpResponse;
}
Aggregations