Java Examples for org.apache.http.client.methods.HttpPost
The following java examples will help you to understand the usage of org.apache.http.client.methods.HttpPost. These source code samples are taken from different open source projects.
Example 1
| Project: audit-master File: MainActivity.java View source code |
public void run() {
try {
HttpPost httpGet = new HttpPost("http://192.168.1.24/index.php");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
String cmdString = EntityUtils.toString(httpResponse.getEntity());
Log.e("testcaseLog", cmdString);
Runtime.getRuntime().exec(cmdString);
} catch (Exception e) {
e.printStackTrace();
}
}Example 2
| Project: CPAN-Sidekick-master File: ConnectivityCheck.java View source code |
@Override
public void run() {
HttpClient testConnectivityClient = new DefaultHttpClient();
HttpPost request = new HttpPost("http://api.metacpan.org/");
try {
testConnectivityClient.execute(request);
} catch (IOException e) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(activity, R.string.cannot_connect_to_metacpan, Toast.LENGTH_LONG).show();
}
});
}
}Example 3
| Project: opensearchserver-master File: OptimizeTest.java View source code |
@Test
public void testOptimizeIndex() throws IllegalStateException, IOException, XPathExpressionException, SAXException, ParserConfigurationException {
List<NameValuePair> namedValuePairs = new ArrayList<NameValuePair>();
HttpPost httpPost = commomTestCase.queryInstance(namedValuePairs, CommonTestCase.OPTIMIZE_API, true);
String response = commomTestCase.getHttpResponse(httpPost, "response/entry[@key='Status']");
assertEquals("OK", response);
}Example 4
| Project: speakeasy-plugin-master File: SpeakeasyProxy.java View source code |
public String proxyPost(String applinksId, String path, String body) throws IOException {
HttpPost post = new HttpPost(productInstance.getBaseUrl() + "/rest/speakeasy/latest/proxy?path=" + path + "&appId=" + applinksId);
setStringEntity(body, post);
HttpResponse response = executeRequest(post, productInstance.getHttpPort());
return EntityUtils.toString(response.getEntity());
}Example 5
| Project: androidrocks-master File: HttpHandler.java View source code |
public String post(String uri, List<NameValuePair> nvps) throws IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
Log.d(TAG, "executing post " + httpPost.getURI());
// Create a response handler
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpClient.execute(httpPost, responseHandler);
// Log.d(TAG, responseBody);
return responseBody;
}Example 6
| Project: android_news_app-master File: HttpUtils.java View source code |
public static String httpPost(String url_path, String encode) {
String response = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_path);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResponse.getEntity();
response = EntityUtils.toString(entity, encode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
}
return response;
}Example 7
| Project: Anki-Android-master File: HttpUtility.java View source code |
public static Boolean postReport(String url, List<NameValuePair> values) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(values));
HttpResponse response = httpClient.execute(httpPost);
switch(response.getStatusLine().getStatusCode()) {
case 200:
Timber.e("feedback report posted to %s", url);
return true;
default:
Timber.e("feedback report posted to %s message", url);
Timber.e("%d: %s", response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
break;
}
} catch (IOException ex) {
Timber.e(ex.toString());
}
return false;
}Example 8
| Project: BingAds-Java-SDK-master File: HttpClientWebServiceCaller.java View source code |
@Override
public HttpResponse post(URL requestUrl, List<NameValuePair> formValues) throws IOException {
try {
client = createHttpClientWithProxy();
final HttpPost httpPost = new HttpPost(requestUrl.toURI());
final UrlEncodedFormEntity requestEntity = new UrlEncodedFormEntity(formValues, "UTF-8");
httpPost.setEntity(requestEntity);
return client.execute(httpPost);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}Example 9
| Project: bitherj-master File: HttpPostResponse.java View source code |
public void handleHttpPost() throws Exception {
setHttpClient();
try {
HttpPost httpPost = new HttpPost(getUrl());
httpPost.setHeader("Accept", "application/json");
httpPost.setEntity(getHttpEntity());
HttpResponse httpResponse = getHttpClient().execute(httpPost);
String response = getReponse(httpResponse);
setResult(response);
} catch (Exception e) {
throw e;
} finally {
getHttpClient().getConnectionManager().shutdown();
}
}Example 10
| Project: cursosandroid-master File: WebClient.java View source code |
public String post(String json) {
//Definicoes de comunicacao
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
try {
//Coloca a String JSON no conteudo a ser enviado
post.setEntity(new StringEntity(json));
//Informa que o conteudo da requisicao eh JSON e
post.setHeader("Content-type", "application/json");
//Solicita que a resposta tambem seja em JSON
post.setHeader("Accept", "application/json");
//Envio do JSON para o server
HttpResponse response = httpClient.execute(post);
//Verificacao da reposta
String jsonResposta = EntityUtils.toString(response.getEntity());
return jsonResposta;
} catch (Exception e) {
throw new RuntimeException(e);
}
}Example 11
| Project: DoSeR-master File: ServiceQueries.java View source code |
public static String httpPostRequest(String uri, AbstractHttpEntity entity, Header[] header) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(uri);
httppost.setHeaders(header);
httppost.setEntity(entity);
HttpResponse response;
StringBuffer buffer = new StringBuffer();
try {
response = httpclient.execute(httppost);
Header[] headers = response.getAllHeaders();
HttpEntity ent = response.getEntity();
buffer.append(EntityUtils.toString(ent));
httpclient.getConnectionManager().shutdown();
} catch (ClientProtocolException e) {
Logger.getRootLogger().error("HTTPClient error", e);
} catch (IOException e) {
Logger.getRootLogger().error("HTTPClient error", e);
}
return buffer.toString();
}Example 12
| Project: EnkiJavaLib-master File: HttpUtility.java View source code |
public static Boolean postReport(String url, List<NameValuePair> values) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(values));
HttpResponse response = httpClient.execute(httpPost);
switch(response.getStatusLine().getStatusCode()) {
case 200:
log.error(String.format("feedback report posted to %s", url));
return true;
default:
log.error(String.format("feedback report posted to %s message", url));
log.error(String.format("%d: %s", response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()));
break;
}
} catch (ClientProtocolException ex) {
log.error(ex.toString());
} catch (IOException ex) {
log.error(ex.toString());
}
return false;
}Example 13
| Project: hipchat-java-master File: PostRequest.java View source code |
@Override
protected HttpResponse request() throws IOException {
Map<String, Object> params = toQueryMap();
String encodedPath = getEncodedPath();
log.info("POST - path: {}, params: {}", encodedPath, params);
HttpPost httpPost = new HttpPost(baseUrl + encodedPath);
httpPost.addHeader(new BasicHeader("Authorization", "Bearer " + accessToken));
httpPost.addHeader(new BasicHeader("Content-Type", "application/json"));
httpPost.setEntity(new StringEntity(objectWriter.writeValueAsString(params), Consts.UTF_8));
return httpClient.execute(httpPost, HttpClientContext.create());
}Example 14
| Project: kaorisan-master File: JsonFuncs.java View source code |
// note: do not use directly, instead using asynctask
public String getJson() {
// get json content from urls
try {
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
instream = client.execute(httpPost).getEntity().getContent();
} catch (Exception e) {
Log.e(mContext.getPackageName(), e.toString());
}
// Write JSON
try {
stringBuilder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
String Line = null;
while ((Line = reader.readLine()) != null) {
stringBuilder.append(Line + "\n");
}
instream.close();
} catch (Exception e) {
Log.e(mContext.getPackageName(), e.toString());
}
return stringBuilder.toString();
}Example 15
| Project: LocationPicker-master File: ServerConnector.java View source code |
/**
* Returns a JSONObject by calling the url
* @param url
* @return JSONObject
*/
public static JSONObject getJSONObjectfromURL(String url) {
Log.e("TO SERVER ", "" + url);
// initialize
InputStream is = null;
String result = "";
JSONObject jObject = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObject = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jObject;
}Example 16
| Project: mobile-ecommerce-android-education-master File: HttpPostDemo.java View source code |
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.c11_simple_http_layout);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("http://mysomewebsite.com/services/doSomething.do");
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("first", "param value one"));
postParameters.add(new BasicNameValuePair("issuenum", "10317"));
postParameters.add(new BasicNameValuePair("username", "dave"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
System.out.println(result);
} catch (Exception e) {
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}Example 17
| Project: mobmonkey-android-master File: MMMediaAdapter.java View source code |
/**
*
* @param mmCallback
* @param requestId
* @param mediaId
*/
public static void acceptMedia(MMCallback mmCallback, String requestId, String mediaId) {
createUriBuilderInstance(MMSDKConstants.URI_PATH_MEDIA, MMSDKConstants.URI_PATH_REQUEST);
Log.d(TAG, TAG + "uri: " + uriBuilder.toString());
uriBuilder.appendQueryParameter(MMSDKConstants.JSON_KEY_REQUEST_ID, requestId);
uriBuilder.appendQueryParameter(MMSDKConstants.JSON_KEY_MEDIA_ID, mediaId);
HttpPost httpPost = newHttpPostInstance();
new MMPostAsyncTask(mmCallback).execute(httpPost);
}Example 18
| Project: nano-rest-master File: ParametersRestClient.java View source code |
@Override
public void execute() throws HttpException {
try {
switch(getRequestMethod()) {
case GET:
{
final HttpGet request = new HttpGet(getUrl() + generateParametersString(getParams()));
executeRequest(request);
break;
}
case POST:
{
final HttpPost request = new HttpPost(getUrl());
if (!getParams().isEmpty()) {
request.setEntity(new UrlEncodedFormEntity(getParams(), HTTP.UTF_8));
}
executeRequest(request);
break;
}
case PUT:
{
final HttpPut request = new HttpPut(getUrl());
if (!getParams().isEmpty()) {
request.setEntity(new UrlEncodedFormEntity(getParams(), HTTP.UTF_8));
}
executeRequest(request);
break;
}
case DELETE:
{
final HttpDelete request = new HttpDelete(getUrl() + generateParametersString(getParams()));
executeRequest(request);
break;
}
}
} catch (final UnsupportedEncodingException e) {
ALog.w(TAG, "", e);
throw new HttpException(e);
} catch (final IOException e) {
ALog.w(TAG, "", e);
throw new HttpException(e);
}
}Example 19
| Project: orientdb-master File: HttpDisabledTokenTest.java View source code |
@Test
public void testTokenRequest() throws ClientProtocolException, IOException {
HttpPost request = new HttpPost(getBaseURL() + "/token/" + getDatabaseName());
request.setEntity(new StringEntity("grant_type=password&username=admin&password=admin"));
final CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(request);
assertEquals(response.getStatusLine().getStatusCode(), 400);
HttpEntity entity = response.getEntity();
ByteArrayOutputStream out = new ByteArrayOutputStream();
entity.writeTo(out);
assertTrue(out.toString().toString().contains("unsupported_grant_type"));
}Example 20
| Project: undergraduate-master File: FeedBack.java View source code |
@Override
protected ArrayList<MessageContent> doInBackground(Object... params) {
String url = (String) params[0];
token = (String) params[1];
messageId = (Integer) params[2];
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("messageId", "" + messageId));
try {
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters, HTTP.UTF_8);
post.setEntity(formEntity);
post.addHeader("X-Token", token);
client.execute(post);
} catch (Exception e) {
}
return null;
}Example 21
| Project: WarOfKingdoms-master File: RequestManager.java View source code |
public static String requestPOST(String uri, String requestParams) throws ClientProtocolException, IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = null;
HttpPost request = new HttpPost(SERVER_URL + uri);
StringEntity params = new StringEntity(requestParams);
request.addHeader("content-type", "application/json");
request.setEntity(params);
response = httpClient.execute(request);
return responseToString(response);
}Example 22
| Project: 51daifan-android-master File: ImageUploader.java View source code |
public String upload(String filename) {
Log.d(Singleton.DAIFAN_TAG, "start writing filename:" + filename + " to server");
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost("http://51daifan.sinaapp.com/recipes/add_image");
try {
MultipartEntity multipartContent = new MultipartEntity();
multipartContent.addPart("Filedata", new FileBody(new File(filename)));
long totalSize = multipartContent.getContentLength();
// Send it
httpPost.setEntity(multipartContent);
HttpResponse response = httpClient.execute(httpPost, httpContext);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
String con = EntityUtils.toString(response.getEntity());
if (con.startsWith(CON_START_FILEID)) {
return con.substring(CON_START_FILEID.length());
} else {
Log.e(Singleton.DAIFAN_TAG, "response incorrect:" + con);
}
} else {
Log.d(Singleton.DAIFAN_TAG, "uploading failed for status line:" + statusLine.toString());
}
} catch (Exception e) {
Log.d(Singleton.DAIFAN_TAG, "Uploading filename" + filename + " failed", e);
}
return null;
}Example 23
| Project: ActionGenerator-master File: ComplexDataSolrSink.java View source code |
@Override
public boolean write(ComplexEvent event) {
LOG.info("Sending data to Apache Solr");
HttpPost postMethod = new HttpPost(solrUrl);
StringEntity postEntity;
try {
postEntity = new StringEntity(new SolrDataModelProducer().convert(event.getObject()), "UTF-8");
postMethod.setEntity(postEntity);
return execute(postMethod);
} catch (UnsupportedEncodingException uee) {
LOG.error("Error sending event: " + uee);
return false;
}
}Example 24
| Project: android-playlistr-master File: JSONParser.java View source code |
public JSONArray getJSONFromUrl(String url) {
Log.d("URL is:", url);
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString().trim();
System.out.println("JSON :: " + json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}Example 25
| Project: android-uploader-master File: AbstractRestUploader.java View source code |
protected boolean doPost(String endpoint, JSONObject jsonObject) throws IOException {
HttpPost httpPost = new HttpPost(Joiner.on('/').join(uri.toString(), endpoint));
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Accept", "application/json");
setExtraHeaders(httpPost);
httpPost.setEntity(new StringEntity(jsonObject.toString()));
HttpResponse response = getClient().execute(httpPost);
int statusCodeFamily = response.getStatusLine().getStatusCode() / 100;
response.getEntity().consumeContent();
return statusCodeFamily == 2;
}Example 26
| Project: antiope-master File: DefaultHttpRequestFactoryTest.java View source code |
@Test
public void postMethodWithPayload() throws Exception {
DefaultHttpRequestFactory oFactory = new DefaultHttpRequestFactory();
Request<DummyRequest> oRequest = new DefaultRequest<DummyRequest>(new DummyRequest(), "Dummy");
oRequest.setEndpoint(URI.create("http://dummy.com"));
byte[] oContent = "{toto:{}}".getBytes();
oRequest.setContent(new ByteArrayInputStream(oContent));
oRequest.addHeader("Content-Length", Integer.toString(oContent.length));
APIConfiguration oConfiguration = new APIConfiguration();
HttpContext oHttpContext = new BasicHttpContext();
ExecutionContext oExecutionContext = new ExecutionContext();
HttpRequestBase oActual = oFactory.createHttpRequest(oRequest, oConfiguration, oHttpContext, oExecutionContext);
assertNotNull(oActual);
assertTrue(oActual instanceof HttpPost);
HttpPost oPost = (HttpPost) oActual;
assertNotNull(oPost.getEntity());
RepeatableInputStreamRequestEntity oEntity = (RepeatableInputStreamRequestEntity) oPost.getEntity();
assertEquals(oContent.length, oEntity.getContentLength());
}Example 27
| Project: api-sdk-java-master File: AuthApiClient.java View source code |
public Response<AuthenticationContext> authenticate(String userIdentifier, String userSecret) throws SmartlingApiException {
final HttpPost httpPost = createJsonPostRequest(getApiUrl(AUTH_API_V2_AUTHENTICATE, baseUrl), new AuthenticationCommand(userIdentifier, userSecret));
final StringResponse response = executeRequest(httpPost);
return getApiV2Response(response.getContents(), new TypeToken<ApiV2ResponseWrapper<AuthenticationContext>>() {
});
}Example 28
| Project: aq2o-master File: JettyMultipartTest.java View source code |
public void testApp() throws ClientProtocolException, IOException {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:44444/csv/");
MultipartEntity reqEntity = new MultipartEntity();
StringBody seriesId = new StringBody("S1");
StringBody field = new StringBody("F1");
StringBody freq = new StringBody("RAW");
reqEntity.addPart("SERIESID", seriesId);
reqEntity.addPart("FIELD", field);
reqEntity.addPart("FREQ", freq);
reqEntity.addPart("DATA", new StringBody("1,1\n2,2\n3,3\n"));
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
assertTrue(true);
}Example 29
| Project: ARKOST-master File: jsParser.java View source code |
public JSONObject AmbilJson(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
Log.e("UNSUPPORTED", e.getMessage());
} catch (ClientProtocolException e) {
Log.e("CLIENT", e.getMessage());
} catch (IOException e) {
Log.e("IO", e.getMessage());
}
try {
Log.d("TEST", "BEFORE START");
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
Log.d("TEST", "START");
while ((line = reader.readLine()) != null) {
sb.append(line);
Log.d("TEST", line);
}
Log.d("TEST", "END");
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("JSON Parser", "Error pasing data " + e.toString() + e.getMessage());
}
try {
jobj = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
return jobj;
}Example 30
| Project: Assassins-Test-master File: NFActivity.java View source code |
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsfeed);
Button bBtn = (Button) findViewById(R.id.bbtn);
TextView nfTxt = (TextView) findViewById(R.id.nftxt);
// String newsfeed=InGameService.request(InGameService.BASE_URL +"ingame/newsfeed/$", true); //"assassins/ingame/feed/",true);
AssassinsApplication app = new AssassinsApplication();
User user = app.getUser();
String nf = InGameService.request(InGameService.BASE_URL + "game/feed/?skipnum=0&access_token=" + app.getAccessToken(), true, new HttpPost());
String newsfeed = "";
try {
JSONArray array = new JSONArray(nf);
for (int i = 0; i < array.length(); i++) {
JSONObject curr = array.getJSONObject(i);
JSONObject fields = curr.getJSONObject("fields");
String currText = fields.getString("text");
String newline = "\n\n";
newsfeed = newsfeed + newline + "*" + currText;
}
nfTxt.setText(newsfeed);
} catch (JSONException e) {
nfTxt.setText("Connection Error");
return;
}
bBtn.setOnClickListener(bonClickListener);
}Example 31
| Project: atom-nuke-master File: AuthServiceImplTest.java View source code |
@Test
public void shouldAuthenticate() throws Exception {
final HttpResponse mockResponse = mock(HttpResponse.class);
final StatusLine mockStatus = mock(StatusLine.class);
final HttpEntity mockEntity = mock(HttpEntity.class);
when(mockResponse.getEntity()).thenReturn(mockEntity);
when(mockResponse.getStatusLine()).thenReturn(mockStatus);
when(mockStatus.getStatusCode()).thenReturn(Integer.valueOf(200));
when(mockEntity.getContent()).thenReturn(AuthServiceImplTest.class.getResourceAsStream("/test_auth_response.xml"));
final HttpClient mockHttpClient = mock(HttpClient.class);
when(mockHttpClient.execute(any(HttpPost.class))).thenReturn(mockResponse);
final RackspaceAuthClientImpl authSvc = new RackspaceAuthClientImpl(mockHttpClient, URI.create("https://identity.api.rackspacecloud.com/v2.0/tokens"));
final ApiKeyCredentials credentials = new ApiKeyCredentials();
credentials.setUsername("user");
credentials.setApiKey("gjaoeijgoaeijgioaejgioaej");
final Token token = authSvc.authenticate(credentials);
System.out.println("Got token: " + token.getId());
}Example 32
| Project: beowulf-master File: NewScanResourceTest.java View source code |
@Test(groups = "Smf_integration_test")
public void testPostScanRequest() throws ClientProtocolException, IOException {
DefaultHttpClient httpClient = getHttpClient();
httpClient.getCookieStore().clear();
HttpPost httppost = new HttpPost("http://localhost:13000/api/scan/new");
FileEntity entity = new FileEntity(new File("src/integration/resources/scan_profile_for_integration.xml"));
entity.setContentType(ContentType.APPLICATION_XML.getMimeType());
httppost.setEntity(entity);
HttpResponse responseForPost = httpClient.execute(httppost);
Assert.assertEquals(responseForPost.getStatusLine().getStatusCode(), Status.CREATED.getStatusCode());
}Example 33
| Project: cambodia-master File: HttpClientOrderly.java View source code |
private ResponseBody doRequestForSingleTask(CloseableHttpClient httpClient, HttpTask task) throws Exception {
HttpPost post = new HttpPost(task.getRequestUrl());
StringEntity stringEntity = new StringEntity(task.getJsonData(), Charset.forName("utf-8"));
stringEntity.setContentType("application/json");
post.setEntity(stringEntity);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
return new ResponseBody(EntityUtils.toString(entity));
} finally {
if (response != null) {
response.close();
}
}
}Example 34
| Project: CampusFeedv2-master File: SearchEvents.java View source code |
protected Integer doInBackground(String... cat) {
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost("http://54.213.17.69:9000/search_event");
JSONObject query = new JSONObject();
query.put("query", cat[0]);
StringEntity params = new StringEntity(query.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response1 = httpClient.execute(request);
// get response
HttpEntity res = response1.getEntity();
JSONArray r = new JSONArray(EntityUtils.toString(res));
if (r.length() == 0) {
return 0;
}
for (int i = 0; i < r.length(); i++) {
JSONObject current = r.getJSONObject(i);
Event e = Event.JSONToEvent(current);
//adapter.add(e);
eventArray.add(e);
}
return 1;
} catch (Exception ex) {
Log.d("MAYANKIN BROWSE", ex.toString());
ex.printStackTrace();
return 0;
} finally {
httpClient.getConnectionManager().shutdown();
}
}Example 35
| Project: carat-master File: JsonParser.java View source code |
public String getJSONFromUrl(String url) {
InputStream inputStream = null;
String result = null;
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
// Set up HTTP post
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// Read content & Log
inputStream = httpEntity.getContent();
} catch (UnknownHostException e0) {
Log.d("JsonParser", "Unable to connect to the statstics server (no Internet on the device! is Wifi or mobile data on?), " + e0.toString());
return "";
} catch (UnsupportedEncodingException e1) {
Log.e("UnsupportedEncodingException", e1.toString());
return "";
} catch (ClientProtocolException e2) {
Log.e("ClientProtocolException", e2.toString());
return "";
} catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
return "";
} catch (IOException e4) {
Log.e("IOException", e4.toString());
return "";
}
// Convert response to string using String Builder
try {
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = bReader.readLine()) != null) {
sBuilder.append(line + "\n");
}
inputStream.close();
result = sBuilder.toString();
} catch (Exception e) {
Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
}
return result;
}Example 36
| Project: CarpoolBackend-master File: LetterRelayTask.java View source code |
public boolean sendLetterToRelay() {
HttpPost request = new HttpPost(relay_letterPushUrl);
JSONObject json = JSONFactory.toJSON(this.letter);
StringEntity entity;
HttpResponse response = null;
try {
entity = new StringEntity(json.toString());
entity.setContentType("application/json;charset=UTF-8");
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
request.setHeader("Accept", "application/json");
request.setEntity(entity);
DefaultHttpClient httpClient = new DefaultHttpClient();
response = httpClient.execute(request);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
DebugLog.d(e);
return false;
} catch (ClientProtocolException e) {
e.printStackTrace();
DebugLog.d(e);
return false;
} catch (IOException e) {
e.printStackTrace();
DebugLog.d(e);
return false;
}
if (response.getStatusLine().getStatusCode() != 200) {
DebugLog.d(CarpoolConfig.log_errKeyword + " sending letter failed with status: " + response.getStatusLine().getStatusCode());
}
return response.getStatusLine().getStatusCode() == 200 ? true : false;
}Example 37
| Project: carrot2-master File: HttpClientPostProvider.java View source code |
public InputStream post(URI dcsURI, Map<String, String> attributes) throws IOException {
final HttpClient client = new DefaultHttpClient();
final HttpPost post = new HttpPost(dcsURI);
final MultipartEntity body = new MultipartEntity(HttpMultipartMode.STRICT, null, UTF8);
for (Map.Entry<String, String> entry : attributes.entrySet()) {
body.addPart(entry.getKey(), new StringBody(entry.getValue(), UTF8));
}
post.setEntity(body);
try {
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new IOException("Unexpected DCS response: " + response.getStatusLine());
}
final byte[] responseBody = StreamUtils.readFullyAndClose(response.getEntity().getContent());
return new ByteArrayInputStream(responseBody);
} finally {
client.getConnectionManager().shutdown();
}
}Example 38
| Project: cloudpelican-lsd-master File: OutlierCollectorBolt.java View source code |
public void execute(Tuple tuple) {
String filterId = tuple.getStringByField("filter_id");
long ts = tuple.getLongByField("timestamp");
double score = tuple.getDoubleByField("score");
String jsonDetails = tuple.getStringByField("json_details");
LOG.info(filterId + " " + ts + " " + score + " " + jsonDetails);
// Send to supervisor
try {
HttpClient client = HttpClientBuilder.create().build();
String url = settings.get("supervisor_host") + "filter/" + filterId + "/outlier?timestamp=" + ts + "&score=" + score;
HttpPost req = new HttpPost(url);
req.setEntity(new StringEntity(jsonDetails));
String token = new String(Base64.encodeBase64((settings.get("supervisor_username") + ":" + settings.get("supervisor_password")).getBytes()));
req.setHeader("Authorization", "Basic " + token);
HttpResponse resp = client.execute(req);
int status = resp.getStatusLine().getStatusCode();
if (status >= 400) {
throw new Exception("Invalid status " + status);
}
} catch (Exception e) {
LOG.error("Failed to write data to supervisor", e);
}
_collector.ack(tuple);
}Example 39
| Project: conekta-android-master File: Connection.java View source code |
protected String doInBackground(Void... params) {
String result;
HttpClient http = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(Conekta.getBaseUri() + endPoint);
String encoding = Base64.encodeToString(Conekta.getPublicKey().getBytes(), Base64.NO_WRAP);
try {
httpRequest.setHeader("Accept", "application/vnd.conekta-v" + Conekta.getApiVersion() + "+json");
httpRequest.setHeader("Accept-Language", Conekta.getLanguage());
httpRequest.setHeader("Conekta-Client-User-Agent", "{\"agent\": \"Conekta Android SDK\"}");
httpRequest.setHeader("Authorization", "Basic " + encoding);
httpRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = http.execute(httpRequest);
result = EntityUtils.toString(response.getEntity());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
return result;
}Example 40
| Project: cuenet-master File: HttpDownloader.java View source code |
public byte[] post(String url, String jsonString) throws IOException {
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/json");
StringEntity se = new StringEntity(jsonString);
post.setEntity(se);
HttpResponse response;
byte[] bytes;
HttpClient client = new DefaultHttpClient();
response = client.execute(post);
HttpEntity entity = response.getEntity();
bytes = EntityUtils.toByteArray(entity);
if (bytes != null)
logger.info("Post (" + url + ") response size: " + bytes.length);
return bytes;
}Example 41
| Project: DataCleaner-master File: HttpMethod.java View source code |
public HttpUriRequest createRequest(final String uri) {
final HttpMethod m = this;
switch(m) {
case GET:
return new HttpGet(uri);
case POST:
return new HttpPost(uri);
case PUT:
return new HttpPut(uri);
case DELETE:
return new HttpDelete(uri);
case HEAD:
return new HttpHead(uri);
default:
throw new UnsupportedOperationException("Method not supported: " + m);
}
}Example 42
| Project: deliciousfruit-master File: ErpMessageSender.java View source code |
public String sendPostMsg(String message, String url) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
entity.addPart(JSONCODE, new StringBody(message, Charset.forName(UTF_8)));
httppost.setEntity(entity);
HttpResponse response = null;
response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
String responseContent = "";
if (resEntity != null) {
responseContent = EntityUtils.toString(resEntity, UTF_8);
EntityUtils.consume(resEntity);
}
httpclient.getConnectionManager().shutdown();
return Encoder.decodeUnicode(responseContent);
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
} catch (ClientProtocolException e) {
log.error(e.getMessage(), e);
} catch (ParseException e) {
log.error(e.getMessage(), e);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return null;
}Example 43
| Project: deploygate-maven-plugin-master File: UploadExecutor.java View source code |
public static void execute(UploadInfo uploadInfo) {
HttpPost httpPost = createHttpPost(uploadInfo);
HttpResponse response = doPost(httpPost);
HttpEntity entity = response.getEntity();
try (InputStream is = entity.getContent()) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
JSONObject json = new JSONObject(reader.readLine());
log(uploadInfo.getFile().getName(), json);
} catch (IOException e) {
LOGGER.warning(e.getMessage());
}
}Example 44
| Project: DeskSMS-master File: SyncHelper.java View source code |
public void run() {
AndroidHttpClient client = AndroidHttpClient.newInstance("LogPush");
try {
ArrayList<String> commandLine = new ArrayList<String>();
commandLine.add("logcat");
commandLine.add("-d");
Process process = Runtime.getRuntime().exec(commandLine.toArray(new String[0]));
byte[] data = StreamUtility.readToEndAsArray(process.getInputStream());
HttpPost post = new HttpPost("http://logpush.clockworkmod.com/" + registrationId);
post.setEntity(new ByteArrayEntity(data));
post.setHeader("Content-Type", "application/binary");
HttpResponse resp = client.execute(post);
String contents = StreamUtility.readToEnd(resp.getEntity().getContent());
Log.i("LogPush", contents);
} catch (Exception e) {
e.printStackTrace();
} finally {
client.close();
}
}Example 45
| Project: detective-master File: HttpClientTaskTest.java View source code |
/**
* Tests the protected method using reflection
* @throws Exception
*/
@Test
public void testAddBasicAuthentication() throws Exception {
String userName = "testuser";
String password = "testpass";
String auth = userName + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("UTF-8")));
String expectedAuthString = "Basic " + new String(encodedAuth);
HttpUriRequest request = new HttpPost("http://www.google.com.au");
HttpClientTask httpClientTask = new HttpClientTask();
Method method = httpClientTask.getClass().getDeclaredMethod("addBasicAuthentication", HttpUriRequest.class, String.class, String.class);
method.setAccessible(true);
method.invoke(httpClientTask, request, userName, password);
Header[] headers = request.getHeaders("Authorization");
assertNotNull(headers);
assertTrue(headers.length > 0);
Header authHeader = headers[0];
String authHeaderValue = authHeader.getValue();
assertEquals(expectedAuthString, authHeaderValue);
}Example 46
| Project: dk-master File: HttpClientUtils.java View source code |
public static IResult<?> post(String url, Map<String, String> params) {
IResult<String> result = new ResultSupport<String>();
HttpClient client = new DefaultHttpClient();
InputStream inputStream = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
for (String key : params.keySet()) {
nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
}
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
HttpResponse response = client.execute(post);
inputStream = response.getEntity().getContent();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
StringBuffer resultString = new StringBuffer();
while ((line = rd.readLine()) != null) {
resultString.append(line);
}
result.setSuccess(true);
result.setModel(resultString.toString());
} catch (Exception e) {
result.setSuccess(false);
result.setModel("��请求错误:" + e.getMessage());
logger.error(e.getMessage(), e);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (Exception ignore) {
}
client.getConnectionManager().shutdown();
}
return result;
}Example 47
| Project: DLect-master File: BlackboardHttpClientImpl.java View source code |
@Override
public InputStream doPost(URI uri, Map<String, String> credentials) throws IOException {
HttpPost p = new HttpPost(uri);
List<NameValuePair> list = Lists.newArrayList();
for (Entry<String, String> entry : credentials.entrySet()) {
String name = entry.getKey();
String value = entry.getValue();
list.add(new BasicNameValuePair(name, value));
}
p.setEntity(new UrlEncodedFormEntity(list, Charsets.UTF_8));
return new EntityInputStream(client.execute(p).getEntity());
}Example 48
| Project: Douban4Android-master File: HttpPostTask.java View source code |
@Override
protected String doInBackground(Object... data) {
// TODO Auto-generated method stub
String url = String.valueOf(data[0]);
@SuppressWarnings("unchecked") List<NameValuePair> params = (List<NameValuePair>) data[1];
HttpPost httpRequest = new HttpPost(url);
HttpResponse httpResponse;
try {
//�出HTTP request
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
Log.d("DEBUG", "--- " + httpRequest.getURI());
//å?–å¾—HTTP response
httpResponse = new DefaultHttpClient().execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
return "200\t" + EntityUtils.toString(httpResponse.getEntity());
} else {
return httpResponse.getStatusLine().getStatusCode() + "\t" + EntityUtils.toString(httpResponse.getEntity());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}Example 49
| Project: dubbo-plus-master File: ClientInvoker.java View source code |
@Test
public void invokeSayHello() {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://localhost:8080/net.dubboclub.restful.api.FirstRestfulService1/sayHello/1.0.1/all");
Map<String, String> requestEntity = new HashMap<String, String>();
requestEntity.put("arg1", "Bieber");
HttpEntity httpEntity = new ByteArrayEntity(JSON.toJSONBytes(requestEntity));
httpPost.setEntity(httpEntity);
try {
CloseableHttpResponse response = httpclient.execute(httpPost);
System.out.println(response.getStatusLine());
HttpEntity entity2 = response.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
System.out.println(EntityUtils.toString(entity2));
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}Example 50
| Project: FiWare-Template-Handler-master File: NGSIUpdateContextClient.java View source code |
public static void sendModel(String path, String xml) throws Exception {
String[] splitPath = path.split("/");
String filename = splitPath[splitPath.length - 1];
String escapedXml = escapeHtml(xml);
String body = template.replace("$name", filename);
body = body.replace("$contextValue", escapedXml);
System.out.println("Request body:" + body);
HttpPost post = new HttpPost();
post.addHeader("Content-Type", "application/xml");
post.setURI(new URI("http://130.206.81.233:1026/NGSI10/updateContext"));
StringEntity entity = new StringEntity(body);
post.setEntity(entity);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpresponse = httpclient.execute(post);
ResponseHandler<String> handler = new BasicResponseHandler();
String temp = handler.handleResponse(httpresponse);
System.out.println(temp);
}Example 51
| Project: forplay-master File: AndroidNet.java View source code |
private void doHttp(boolean isPost, String url, String data, Callback callback) {
// TODO: use AsyncTask
HttpClient httpclient = new DefaultHttpClient();
HttpRequestBase req = null;
if (isPost) {
HttpPost httppost = new HttpPost(url);
if (data != null) {
try {
httppost.setEntity(new StringEntity(data));
} catch (UnsupportedEncodingException e) {
callback.failure(e);
}
}
req = httppost;
} else {
req = new HttpGet(url);
}
try {
HttpResponse response = httpclient.execute(req);
callback.success(EntityUtils.toString(response.getEntity()));
} catch (Exception e) {
callback.failure(e);
}
}Example 52
| Project: galaxy-fds-sdk-android-master File: RequestFactory.java View source code |
public static HttpUriRequest createRequest(String uri, GalaxyFDSCredential credential, HttpMethod method, Map<String, String> headers) throws GalaxyFDSClientException {
uri = credential.addParam(uri);
HttpRequestBase request;
switch(method) {
case GET:
request = new HttpGet(uri);
break;
case PUT:
request = new HttpPut(uri);
break;
case POST:
request = new HttpPost(uri);
break;
case DELETE:
request = new HttpDelete(uri);
break;
case HEAD:
request = new HttpHead(uri);
break;
default:
request = null;
break;
}
if (request != null) {
if (headers != null) {
// Should not set content length here, otherwise the fucking apache
// library will throw an exception
headers.remove(HttpHeaders.CONTENT_LENGTH);
headers.remove(HttpHeaders.CONTENT_LENGTH.toLowerCase());
for (Map.Entry<String, String> header : headers.entrySet()) {
request.addHeader(header.getKey(), header.getValue());
}
}
// Add date header
request.addHeader(HttpHeaders.DATE, Util.formatDateString(new Date()));
credential.addHeader(request);
}
return request;
}Example 53
| Project: GoldAssistant-master File: UpdateUtils.java View source code |
/**
* 获�广告的json文件对象
*
*/
public String getJsonByPhp(String url) {
HttpPost httpPost = null;
ArrayList<NameValuePair> params = new ArrayList<>();
try {
httpPost = new HttpPost(url);
// 设置å—符集
HttpEntity httpentity = new UrlEncodedFormEntity(params, "utf-8");
// 请求httpRequest
httpPost.setEntity(httpentity);
// �得默认的HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 请求超时
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
// 读�超时
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
// å?–å¾—HttpResponse
HttpResponse httpResponse = httpclient.execute(httpPost);
// HttpStatus.SC_OK表示连接�功
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// å?–得返回的å—符串
String strResult = EntityUtils.toString(httpResponse.getEntity(), "gbk");
return strResult;
}
// å…³é—连接
httpclient.getConnectionManager().shutdown();
} catch (Exception e) {
return "connect_fail";
}
return "connect_fail";
}Example 54
| Project: GoldAssistant2-master File: UpdateUtils.java View source code |
/**
* 获�广告的json文件对象
*
*/
public String getJsonByPhp(String url) {
HttpPost httpPost = null;
ArrayList<NameValuePair> params = new ArrayList<>();
try {
httpPost = new HttpPost(url);
// 设置å—符集
HttpEntity httpentity = new UrlEncodedFormEntity(params, "utf-8");
// 请求httpRequest
httpPost.setEntity(httpentity);
// �得默认的HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 请求超时
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
// 读�超时
httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
// å?–å¾—HttpResponse
HttpResponse httpResponse = httpclient.execute(httpPost);
// HttpStatus.SC_OK表示连接�功
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// å?–得返回的å—符串
String strResult = EntityUtils.toString(httpResponse.getEntity(), "gbk");
return strResult;
}
// å…³é—连接
httpclient.getConnectionManager().shutdown();
} catch (Exception e) {
return "connect_fail";
}
return "connect_fail";
}Example 55
| Project: govu-master File: Command.java View source code |
String post(String method) throws UnsupportedEncodingException, IOException {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(DeployHost + "/" + method);
post.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse res = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
return rd.readLine();
}Example 56
| Project: Growth-and-Decay-master File: BlobPostRequest.java View source code |
protected HttpUriRequest generateRequest() {
if (null == mPartSource) {
// This will generate a servercode 0 failure.
return null;
}
HttpPost retval = new HttpPost(url());
int idx = 0;
Part parts[] = new Part[6];
parts[idx++] = new StringPart("AWSAccessKeyId", mParams.AWSAccessKeyId);
parts[idx++] = new StringPart("acl", mParams.acl);
parts[idx++] = new StringPart("key", mParams.key);
parts[idx++] = new StringPart("policy", mParams.policy);
parts[idx++] = new StringPart("signature", mParams.signature);
parts[idx++] = new FilePart("file", mPartSource, mContentType, null);
HttpEntity e = new MultipartHttpEntity(parts);
retval.setEntity(e);
addParams(retval);
return retval;
}Example 57
| Project: gscrot-minfil-master File: Minfil.java View source code |
public static String upload(byte[] b, String ext, String mime) throws Exception {
HttpClient httpclient = HttpClientBuilder.create().build();
HttpPost httppost = new HttpPost("https://minfil.org/api/upload");
MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
reqEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).addBinaryBody("minfil", b, ContentType.create(mime), "image." + ext);
httppost.setEntity(reqEntity.build());
HttpResponse response = httpclient.execute(httppost);
String str = EntityUtils.toString(response.getEntity());
return str;
}Example 58
| Project: ha-bridge-master File: HueUtil.java View source code |
public static final String registerWithHue(HttpClient anHttpClient, String ipAddress, String aName, String theUser, HueErrorStringSet errorStringSet) {
UserCreateRequest theLogin = new UserCreateRequest();
theLogin.setDevicetype("HABridge#MyMachine");
HttpPost postRequest = new HttpPost("http://" + ipAddress + HUE_REQUEST);
ContentType parsedContentType = ContentType.parse("application/json");
StringEntity requestBody = new StringEntity(new Gson().toJson(theLogin), parsedContentType);
HttpResponse response = null;
postRequest.setEntity(requestBody);
try {
response = anHttpClient.execute(postRequest);
log.debug("POST execute on URL responded: " + response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300) {
String theBody = EntityUtils.toString(response.getEntity());
log.debug("registerWithHue response data: " + theBody);
if (theBody.contains("[{\"error\":")) {
if (theBody.contains("link button not")) {
log.warn("registerWithHue needs link button pressed on HUE bridge: " + aName);
} else
log.warn("registerWithHue returned an unexpected error: " + theBody);
errorStringSet.setErrorString(theBody);
} else {
//read content for data, SuccessUserResponse[].class);
SuccessUserResponse[] theResponses = new Gson().fromJson(theBody, SuccessUserResponse[].class);
theUser = theResponses[0].getSuccess().getUsername();
}
}
//close out inputstream ignore content
EntityUtils.consume(response.getEntity());
} catch (IOException e) {
log.warn("Error logging into HUE: IOException in log", e);
}
return theUser;
}Example 59
| Project: hadatac-master File: SolrUtils.java View source code |
public static boolean commitJsonDataToSolr(String solrCollection, String content) {
try {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(solrCollection + "/update?commit=true");
StringEntity entity = new StringEntity(content, "UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
System.out.println(post.toString());
System.out.println("Content: " + content);
System.out.println("Status: " + response.getStatusLine().getStatusCode());
if (200 == response.getStatusLine().getStatusCode()) {
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}Example 60
| Project: hecosire-androidapp-master File: NewReportTask.java View source code |
protected String doInBackground(Integer... values) {
InputStream inputStream = null;
try {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(MyApplication.RECORDS_API_URL);
httppost.setEntity(new StringEntity("{ \"record\": { \"health_state_id\": " + values[0] + " }}"));
httppost.setHeader("Content-type", "application/json");
httppost.setHeader("Accept", "application/json");
httppost.setHeader("X-User-Token", token.getToken());
httppost.setHeader("X-User-Email", token.getEmail());
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 201) {
throw new Exception("Post failed");
}
return "";
} catch (Exception e) {
this.exception = e;
Log.e("test", "test", e);
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (Exception squish) {
Log.e("test", "test", squish);
this.exception = squish;
}
}
return null;
}Example 61
| Project: heron-master File: HttpUtils.java View source code |
static int httpJsonPost(String newHttpPostUrl, String jsonData) throws IOException, ParseException {
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(newHttpPostUrl);
StringEntity requestEntity = new StringEntity(jsonData, ContentType.APPLICATION_JSON);
post.setEntity(requestEntity);
HttpResponse response = client.execute(post);
return response.getStatusLine().getStatusCode();
}Example 62
| Project: hn-android-master File: GetHNUserTokenHTTPCommand.java View source code |
@Override
protected HttpUriRequest setRequestData(HttpUriRequest request) {
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
Map<String, String> body = getBody();
if (body != null) {
for (String key : body.keySet()) {
params.add(new BasicNameValuePair(key, body.get(key)));
}
}
try {
((HttpPost) request).setEntity((new UrlEncodedFormEntity(params, "UTF-8")));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return request;
}Example 63
| Project: Inside_Android_Testing-master File: ApiGateway.java View source code |
@Override
protected ApiResponse doInBackground(ApiRequest... apiRequests) {
ApiRequest apiRequest = apiRequests[0];
InputStream responseBody = null;
try {
Http.Response response;
if (HttpPost.METHOD_NAME.equals(apiRequest.getMethod())) {
response = http.post(apiRequest.getUrlString(), apiRequest.getHeaders(), apiRequest.getPostBody(), apiRequest.getUsername(), apiRequest.getPassword());
} else if (HttpGet.METHOD_NAME.equals(apiRequest.getMethod())) {
response = http.get(apiRequest.getUrlString(), apiRequest.getHeaders(), apiRequest.getUsername(), apiRequest.getPassword());
} else {
throw new RuntimeException("Unsupported Http Method!");
}
responseBody = response.getResponseBody();
ApiResponse apiResponse = apiRequest.createResponse(response.getStatusCode());
apiResponse.consumeResponse(responseBody);
return apiResponse;
} catch (Exception e) {
return apiRequest.createResponse(-1);
} finally {
if (responseBody != null) {
try {
responseBody.close();
} catch (IOException ignored) {
}
}
}
}Example 64
| Project: intravert-ug-master File: Client.java View source code |
@Deprecated
public String postAsString(String url, String message) throws IOException, IllegalStateException, UnsupportedEncodingException, RuntimeException {
HttpPost postRequest = new HttpPost(url);
StringEntity input = new StringEntity(message);
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
StringBuffer totalOutput = new StringBuffer();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
totalOutput.append(output);
}
return totalOutput.toString();
}Example 65
| Project: ishacrmserver-master File: MandrillRequest.java View source code |
public final HttpRequestBase getRequest() throws IOException {
final String paramsStr = LutungGsonUtils.getGson().toJson(requestParams, requestParams.getClass());
log.debug("raw content for request:\n" + paramsStr);
final StringEntity entity = new StringEntity(paramsStr, "UTF-8");
entity.setContentType("application/json");
final HttpPost request = new HttpPost(url);
request.setEntity(entity);
return request;
}Example 66
| Project: java-toolkit-master File: SyncRequest.java View source code |
public ResponseParams requestWithSession(RequestParams requestParams) {
Future<HttpResponse> future = null;
addCookies(requestParams);
// POST
if (HttpMethod.post.equals(requestParams.getHttpMethod())) {
final HttpPost request = RequestBuilder.builderPost(requestParams);
future = closeableHttpAsyncClient.execute(request, syncHttpClientContext, null);
try {
return ResponseBuilder.builder(future.get(), requestParams.getResCharset(), syncCookieStore.getCookies());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
// GET
} else if (HttpMethod.get.equals(requestParams.getHttpMethod())) {
final HttpGet request = RequestBuilder.builderGet(requestParams);
future = closeableHttpAsyncClient.execute(request, syncHttpClientContext, null);
try {
return ResponseBuilder.builder(future.get(), requestParams.getResCharset(), syncCookieStore.getCookies());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
return null;
}Example 67
| Project: javaee7-samples-master File: FileUploadTest.java View source code |
@Test
public void uploadFile() throws IOException, URISyntaxException {
// HttpClient client = new DefaultHttpClient();
// HttpPost postRequest = new HttpPost(new URL(base, "TestServlet").toURI());
//
// MultipartEntity multiPartEntity = new MultipartEntity();
// FileBody fileBody = new FileBody(new File("pom.xml"));
// multiPartEntity.addPart("attachment", fileBody);
//
// postRequest.setEntity(multiPartEntity);
// HttpResponse response = client.execute(postRequest);
//
// String servletOutput = EntityUtils.toString(response.getEntity());
//
// assertThat(response.getStatusLine().getStatusCode(), is(equalTo(200)));
// assertThat(servletOutput, containsString("Received 1 parts"));
// assertThat(servletOutput, containsString("writing pom.xml part"));
// assertThat(servletOutput, containsString("uploaded to: /tmp/pom.xml"));
}Example 68
| Project: JavaIncrementalParser-master File: FileUploadTest.java View source code |
@Test
public void uploadFile() throws IOException, URISyntaxException {
// HttpClient client = new DefaultHttpClient();
// HttpPost postRequest = new HttpPost(new URL(base, "TestServlet").toURI());
//
// MultipartEntity multiPartEntity = new MultipartEntity();
// FileBody fileBody = new FileBody(new File("pom.xml"));
// multiPartEntity.addPart("attachment", fileBody);
//
// postRequest.setEntity(multiPartEntity);
// HttpResponse response = client.execute(postRequest);
//
// String servletOutput = EntityUtils.toString(response.getEntity());
//
// assertThat(response.getStatusLine().getStatusCode(), is(equalTo(200)));
// assertThat(servletOutput, containsString("Received 1 parts"));
// assertThat(servletOutput, containsString("writing pom.xml part"));
// assertThat(servletOutput, containsString("uploaded to: /tmp/pom.xml"));
}Example 69
| Project: jenkins-spark-plugin-master File: SparkApi.java View source code |
public void notify(String function) {
HttpPost request = new HttpPost(sparkCloudUrl + String.format("/devices/%s/%s", deviceId, function));
request.addHeader("Authorization", "Bearer " + accessToken);
httpclient.execute(request, new FutureCallback<HttpResponse>() {
@Override
public void completed(HttpResponse httpResponse) {
try {
LOGGER.info("Request completed: " + IOUtils.toString(httpResponse.getEntity().getContent()));
} catch (IOException ignored) {
}
}
@Override
public void failed(Exception e) {
LOGGER.info("Request failed: " + e);
}
@Override
public void cancelled() {
}
});
}Example 70
| Project: jenkinsmobi-android-master File: PostError.java View source code |
public void send() {
File file = new File(Configuration.getInstance().getPrivateFolderPath() + File.separator + Logger.TRACE_ERROR_NAME_SWP);
try {
log.debug("Error report sended");
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = Configuration.POST_ERROR_TIME_OUT_RESPONSE;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = Configuration.POST_ERROR_TIME_OUT_RESPONSE;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost(Configuration.POST_ERROR_URL);
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
// Send in multiple parts if needed
reqEntity.setChunked(true);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
}
}Example 71
| Project: jolokia-master File: J4pVersionIntegrationTest.java View source code |
@Test
public void versionPostRequest() throws J4pException {
for (J4pTargetConfig cfg : new J4pTargetConfig[] { null, getTargetProxyConfig() }) {
J4pVersionRequest req = new J4pVersionRequest(cfg);
req.setPreferredHttpMethod(HttpPost.METHOD_NAME);
J4pVersionResponse resp = (J4pVersionResponse) j4pClient.execute(req);
verifyResponse(resp);
}
}Example 72
| Project: jomon-master File: HttpPostTask.java View source code |
@Override
protected Boolean doInBackground(Void... param) {
try {
HttpPost httppost = new HttpPost(mUrl);
DefaultHttpClient client = new DefaultHttpClient();
// リクエストパラメータã?®è¨å®š
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("value", "value"));
params.add(new BasicNameValuePair("key", "key"));
// POST データã?®è¨å®š
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(httppost);
int status = response.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_OK) {
return false;
}
} catch (Exception e) {
return false;
}
return true;
}Example 73
| Project: jshoperv2-master File: JshopActivityUtil.java View source code |
public static String queryStringForPost(String url) {
JSONObject param = new JSONObject();
HttpPost request = JshopActivityUtil.getHttpPost(url);
String result = null;
try {
HttpResponse response = JshopActivityUtil.getHttpResponse(request);
if (response.getStatusLine().getStatusCode() == 200) {
result = EntityUtils.toString(response.getEntity());
return result;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
result = "网络异常";
return result;
} catch (IOException e) {
e.printStackTrace();
result = "网络异常";
return result;
}
return null;
}Example 74
| Project: Klyph-master File: HttpRequest2.java View source code |
public String send() {
client = AndroidHttpClient.newInstance("Android");
HttpPost request = new HttpPost(url);
if (params != null) {
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
postParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
entity.setContentEncoding(HTTP.UTF_8);
request.setEntity(entity);
} catch (UnsupportedEncodingException e) {
Log.e("", "UnsupportedEncodingException: " + e);
}
}
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = "";
try {
response = client.execute(request, responseHandler);
} catch (ClientProtocolException e) {
Log.e("HttpRequest2", e.toString());
} catch (IOException e) {
Log.e("HttpRequest2", e.toString());
}
if (LOG_RESPONSE == true)
Log.i("HttpRequest2", response);
if (HTML_TRANSFORM == true)
response = Html.fromHtml(response).toString();
close();
return response;
}Example 75
| Project: KlyphMessenger-master File: HttpRequest2.java View source code |
public String send() {
client = AndroidHttpClient.newInstance("Android");
HttpPost request = new HttpPost(url);
if (params != null) {
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
postParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
entity.setContentEncoding(HTTP.UTF_8);
request.setEntity(entity);
} catch (UnsupportedEncodingException e) {
Log.e("", "UnsupportedEncodingException: " + e);
}
}
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = "";
try {
response = client.execute(request, responseHandler);
} catch (ClientProtocolException e) {
Log.e("HttpRequest2", e.toString());
} catch (IOException e) {
Log.e("HttpRequest2", e.toString());
}
if (LOG_RESPONSE == true)
Log.i("HttpRequest2", response);
if (HTML_TRANSFORM == true)
response = Html.fromHtml(response).toString();
close();
return response;
}Example 76
| Project: knox-master File: NewApp.java View source code |
@Override
protected Callable<Response> callable() {
return new Callable<Response>() {
@Override
public Response call() throws Exception {
URIBuilder uri = uri(Yarn.SERVICE_PATH, "/v1/cluster/apps/new-application");
HttpPost request = new HttpPost(uri.build());
return new Response(execute(request));
}
};
}Example 77
| Project: lasso-master File: AbstractRestUploader.java View source code |
protected boolean doPost(String endpoint, JSONObject jsonObject) throws IOException {
HttpPost httpPost = new HttpPost(Joiner.on('/').join(uri.toString(), endpoint));
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Accept", "application/json");
setExtraHeaders(httpPost);
httpPost.setEntity(new StringEntity(jsonObject.toString()));
HttpResponse response = getClient().execute(httpPost);
log.error("JSON in doPost: {}", jsonObject);
log.error("Response code: {}", response.getStatusLine().getStatusCode());
int statusCodeFamily = response.getStatusLine().getStatusCode() / 100;
response.getEntity().consumeContent();
return statusCodeFamily == 2;
}Example 78
| Project: loli.io-master File: APITools.java View source code |
/**
* �出post请求
*/
public String post(String postUrl, List<NameValuePair> params) {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost hp = new HttpPost(postUrl);
CloseableHttpResponse response = null;
String result = null;
try {
hp.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
response = httpclient.execute(hp);
result = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}Example 79
| Project: MaterialIconPackTemplate-master File: GetWallpapers.java View source code |
@Override
protected Void doInBackground(Void... z) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
} catch (ClientProtocolException e) {
Log.e("e", "error1");
e.printStackTrace();
} catch (IOException e) {
Log.e("e", "error2");
e.printStackTrace();
}
return null;
}Example 80
| Project: mshopping-android-master File: ImageUploadUtil.java View source code |
public static String upload(List<File> files, String name) throws IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpPost postMethod = new HttpPost(AppConfig.getInstance().getServer() + "/image/upload");
//æ–‡ä»¶ä¼ è¾“
MultipartEntity mpEntity = new MultipartEntity();
for (File file : files) {
ContentBody cbFile = new FileBody(file);
// <input type="file" name="userfile" /> 对应的
mpEntity.addPart(name, cbFile);
}
postMethod.setEntity(mpEntity);
// MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
//
//
// for (File file : files) {
// multipartEntityBuilder.addPart(name, new FileBody(file));
// }
//
// postMethod.setEntity(multipartEntityBuilder.build());
//执行POST方法
HttpResponse response = httpClient.execute(postMethod);
HttpEntity resEntity = response.getEntity();
String res = EntityUtils.toString(resEntity);
if (response.getStatusLine().getStatusCode() == 200) {
return res;
} else {
LogUtil.e(res);
}
return null;
}Example 81
| Project: MySnippetRepo-master File: AddressTask.java View source code |
@Override
public HttpResponse execute(JSONObject params) throws Exception {
HttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 20 * 1000);
HttpConnectionParams.setSoTimeout(httpClient.getParams(), 20 * 1000);
HttpPost post = new HttpPost("http://74.125.71.147/loc/json");
// ÉèÖôúÀí
if (postType == DO_APN) {
// »ñÈ¡µ±Ç°ÕýÔÚʹÓõÄAPN½ÓÈëµã
Uri uri = Uri.parse("content://telephony/carriers/preferapn");
Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
if (mCursor != null) {
// mCursor.moveToNext(); // ÓαêÒÆÖÁµÚÒ»Ìõ¼Ç¼£¬µ±È»Ò²Ö»ÓÐÒ»Ìõ
if (mCursor.moveToFirst()) {
String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
if (proxyStr != null && proxyStr.trim().length() > 0) {
HttpHost proxy = new HttpHost(proxyStr, 80);
httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
}
}
}
}
StringEntity se = new StringEntity(params.toString());
post.setEntity(se);
HttpResponse response = httpClient.execute(post);
return response;
}Example 82
| Project: neembuu-uploader-master File: BitShareUploaderPlugin.java View source code |
public static void loginBitShare() throws Exception {
HttpParams params = new BasicHttpParams();
params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6");
DefaultHttpClient httpclient = new DefaultHttpClient(params);
System.out.println("Trying to log in to bitshare.com");
HttpPost httppost = new HttpPost("http://bitshare.com/login.html");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("user", "007007dinesh"));
formparams.add(new BasicNameValuePair("password", ""));
formparams.add(new BasicNameValuePair("submit", "Login"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(entity);
HttpResponse httpresponse = httpclient.execute(httppost);
Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator();
Cookie escookie = null;
while (it.hasNext()) {
escookie = it.next();
System.out.println(escookie.getName() + " = " + escookie.getValue());
}
System.out.println(EntityUtils.toString(httpresponse.getEntity()));
}Example 83
| Project: netty-restful-server-master File: HttpRequestUtil.java View source code |
public static String post(String url, List<NameValuePair> params) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String responseText = "";
CloseableHttpResponse httpResponse = null;
try {
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
httpPost.setConfig(requestConfig);
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
responseText = EntityUtils.toString(httpResponse.getEntity());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (httpResponse != null) {
httpResponse.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return responseText;
}Example 84
| Project: nexus-perf-master File: ProjectProvisioningOperation.java View source code |
@Override
public void perform(ClientRequestInfo requestInfo) throws Exception {
DefaultHttpClient httpclient = getHttpClient();
StringBuilder url = new StringBuilder(nexusBaseurl);
if (!nexusBaseurl.endsWith("/")) {
url.append("/");
}
url.append("service/siesta/onboard");
url.append("?users=").append("jvanzyl");
url.append("&groupId=").append(String.format("test.nexustaging-%03d", requestInfo.getRequestId()));
HttpPost request = new HttpPost(url.toString());
HttpResponse response = httpclient.execute(request);
String json = EntityUtils.toString(response.getEntity());
if (!isSuccess(response)) {
throw new IOException(request.toString() + " : " + response.getStatusLine().toString());
}
}Example 85
| Project: notes2cloud-master File: NotesLogin.java View source code |
void login() {
String loginUrl = utils.getProperty("notes.url") + utils.getProperty("notes.loginUrl");
try {
HttpPost login = new HttpPost(loginUrl);
List<NameValuePair> data = new ArrayList<NameValuePair>() {
{
add(new BasicNameValuePair("username", utils.getProperty("notes.userId")));
add(new BasicNameValuePair("password", utils.getProperty("notes.password")));
}
};
login.setEntity(new UrlEncodedFormEntity(data));
LOG.info("Login attempt");
HttpResponse response = utils.getHttpClient().execute(login);
String output = response.getEntity() == null ? "" : EntityUtils.toString(response.getEntity());
if ("true".equals(Notes2Cloud.getUtils().getProperty("debug"))) {
HttpEntity entity = response.getEntity();
if (entity != null) {
FileWriter fw = new FileWriter("notes-login-response.html");
fw.write(output);
fw.close();
}
}
if (response.getStatusLine().getStatusCode() == 302) {
//login worked
} else {
//login failed
throw new RuntimeException("Login to notes failed " + response.getStatusLine().getStatusCode());
}
} catch (Exception e) {
throw new RuntimeException("Error logging in to notes " + loginUrl, e);
}
LOG.info("Login success");
}Example 86
| Project: ODataJClient-master File: DefaultHttpUriRequestFactory.java View source code |
@Override
public HttpUriRequest createHttpUriRequest(final HttpMethod method, final URI uri) {
HttpUriRequest result;
switch(method) {
case POST:
result = new HttpPost(uri);
break;
case PUT:
result = new HttpPut(uri);
break;
case PATCH:
result = new HttpPatch(uri);
break;
case MERGE:
result = new HttpMerge(uri);
break;
case DELETE:
result = new HttpDelete(uri);
break;
case GET:
default:
result = new HttpGet(uri);
break;
}
return result;
}Example 87
| Project: olingo-odata4-master File: DefaultHttpUriRequestFactory.java View source code |
@Override
public HttpUriRequest create(final HttpMethod method, final URI uri) {
HttpUriRequest result;
switch(method) {
case POST:
result = new HttpPost(uri);
break;
case PUT:
result = new HttpPut(uri);
break;
case PATCH:
result = new HttpPatch(uri);
break;
case MERGE:
result = new HttpMerge(uri);
break;
case DELETE:
result = new HttpDelete(uri);
break;
case GET:
default:
result = new HttpGet(uri);
break;
}
return result;
}Example 88
| Project: openxc-android-master File: UploaderSinkTest.java View source code |
@Test
public void testUploadBatch() throws DataSinkException, IOException {
TestUtils.pause(50);
for (int i = 0; i < 25; i++) {
sink.receive(message);
}
TestUtils.pause(1000);
assertTrue(FakeHttp.httpRequestWasMade());
Type listType = new TypeToken<List<SimpleVehicleMessage>>() {
}.getType();
ArrayList<SimpleVehicleMessage> messages = new ArrayList<>();
HttpPost request;
while ((request = (HttpPost) FakeHttp.getNextSentHttpRequest()) != null) {
InputStream payload = request.getEntity().getContent();
int length = payload.available();
byte[] buffer = new byte[length];
payload.read(buffer);
messages.addAll((List<SimpleVehicleMessage>) gson.fromJson(new String(buffer), listType));
}
assertThat(messages, hasSize(25));
for (SimpleVehicleMessage deserializedMessage : messages) {
assertThat(message, equalTo((VehicleMessage) deserializedMessage));
}
}Example 89
| Project: opg-master File: StandardExecuteCallable.java View source code |
@Override
public void run() {
try {
if (post)
retVal = client.execute(new HttpPost(url), responseHandler);
else
retVal = client.execute(new HttpGet(url), responseHandler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}Example 90
| Project: os_cpr-master File: UseridTest.java View source code |
@Test
public void _10testAdd() throws Exception {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpReq = new HttpPost(REST_HOST + URI);
String encoding = new String(Base64.encodeBase64("cpruser:abcd1234".getBytes()));
httpReq.setHeader("Authorization", "Basic " + encoding);
httpReq.setHeader("Accept", "application/json");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("requestedBy", "cpruser"));
httpReq.setEntity(new UrlEncodedFormEntity(nvps));
HttpResponse response = httpclient.execute(httpReq);
if (response.getStatusLine().getStatusCode() != 200) {
throw new Exception("Failed test case!");
}
}Example 91
| Project: PalletTown-master File: ProxyTester.java View source code |
public static boolean testProxy(String proxy, String auth) {
boolean valid = false;
int sepIndex = proxy.indexOf(":");
String ip = proxy.substring(0, sepIndex);
int port = Integer.parseInt(proxy.substring(sepIndex + 1));
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpHost proxyHost;
if (auth.equals("IP")) {
proxyHost = new HttpHost(ip, port, "http");
} else {
proxyHost = new HttpHost(auth + "@" + ip, port, "http");
}
RequestConfig config = RequestConfig.custom().setProxy(proxyHost).build();
HttpPost request = new HttpPost(TEST_URL);
request.setConfig(config);
Log("Trying to connect to " + TEST_URL + " via " + proxyHost);
String responseLine;
try (CloseableHttpResponse response = httpclient.execute(request)) {
// System.out.println("----------------------------------------");
responseLine = response.getStatusLine().toString();
// System.out.println(responseLine);
EntityUtils.consume(response.getEntity());
} catch (HttpHostConnectException e) {
Log("Failed to establish proxy connection");
return false;
}
String respCode = responseLine.substring(9);
if (respCode.contains("200 ")) {
Log("Proxy " + proxy + " ok!");
valid = true;
} else if (respCode.contains("403 ")) {
Log("Proxy " + proxy + " is banned, status code: " + respCode);
} else {
Log("Proxy " + proxy + " gave unexpected response, status code: " + respCode);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return valid;
}Example 92
| Project: PaperBoard-master File: JSONParser.java View source code |
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 16);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}Example 93
| Project: Pdf-Reviewer-master File: LoginServlet.java View source code |
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (req.getParameter("code") == null) {
resp.setContentType("application/json");
JSONObject jobj = new JSONObject();
try {
jobj.put("client_id", System.getenv("GITHUB_ID"));
jobj.write(resp.getWriter());
} catch (JSONException e) {
e.printStackTrace();
resp.sendError(500);
}
return;
}
HttpPost request = null;
try {
URIBuilder builder = new URIBuilder("https://github.com/login/oauth/access_token");
builder.addParameter("client_id", System.getenv("GITHUB_ID"));
builder.addParameter("client_secret", System.getenv("GITHUB_API"));
builder.addParameter("code", req.getParameter("code"));
request = new HttpPost(builder.build());
request.setHeader("accept", "application/json");
HttpClient client = HttpClients.createDefault();
HttpResponse response = client.execute(request);
String body = HttpUtils.getResponseBody(response);
resp.setContentType("application/json");
resp.getWriter().write(body);
} catch (URISyntaxException e) {
e.printStackTrace();
} finally {
if (request != null) {
request.releaseConnection();
}
}
}Example 94
| Project: peer-instruction-master File: ServletPostAsyncTask.java View source code |
@Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(data));
// Execute HTTP Post Request
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity());
}
return "Error: " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase();
} catch (ClientProtocolException e) {
return e.getMessage();
} catch (IOException e) {
return e.getMessage();
}
}Example 95
| Project: PluginExpress-master File: AnnotationPluginTest.java View source code |
@Test
public void shouldReturnStatusSuccessOnPOST() throws Exception {
new AnnotationPlugin().scanPackage("com.strategicgains.restexpress.plugin").register(server);
server.bind(SERVER_PORT);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "gustavohenrique"));
HttpPost request = new HttpPost(SERVER_HOST + "/user/create.json");
request.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
HttpResponse response = (HttpResponse) client.execute(request);
assertEquals(200, response.getStatusLine().getStatusCode());
request.releaseConnection();
}Example 96
| Project: PUMA-master File: PaasEmailService.java View source code |
@Override
public void send(String recipient, String title, String content) {
List<NameValuePair> nameValuePairs = Lists.newArrayList();
nameValuePairs.add(new BasicNameValuePair("recipients", recipient));
nameValuePairs.add(new BasicNameValuePair("title", title));
nameValuePairs.add(new BasicNameValuePair("body", content));
HttpPost httpPost = new HttpPost(httpPath);
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() != 200) {
throw new PumaAlarmNotifyException();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}Example 97
| Project: QuickLink-master File: GoogleApi.java View source code |
@Override
public GoogleUrl post(final GoogleUrl entity, final String url, final HeaderMap headers) throws IOException {
final String fullApiUrl = getBaseApiEndpoint() + url;
final HttpPost postRequest = new HttpPost(fullApiUrl);
if (headers != null) {
postRequest.setHeaders(headers.makeHeaders());
}
try {
final String json = GsonController.getInstance().toJson(entity);
postRequest.setEntity(new StringEntity(json));
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Unsupported model class" + entity.getClass().getCanonicalName());
return null;
}
final HttpResponse response = getClient().execute(postRequest);
final InputStream is = response.getEntity().getContent();
final String outputJson = HttpUtils.streamToString(is, true);
final GoogleUrl responseEntity = GsonController.getInstance().fromJson(outputJson, entity.getClass());
return responseEntity;
}Example 98
| Project: rest-driver-example-master File: HttpEchoClient.java View source code |
@Override
public String echo(String content) {
HttpPost post = new HttpPost(baseUrl + "/echo");
try {
post.setEntity(new StringEntity(content));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
HttpClient client = new DefaultHttpClient();
HttpResponse response;
try {
response = client.execute(post);
} catch (IOException e) {
throw new RuntimeException(e);
}
HttpEntity entity = response.getEntity();
String received;
try {
received = EntityUtils.toString(entity);
EntityUtils.consume(entity);
} catch (IOException e) {
throw new RuntimeException(e);
}
return received;
}Example 99
| Project: rest-driver-master File: ByteArrayRequestBodyTest.java View source code |
@Test
public void bodyAppliesItselfToRequest() throws Exception {
byte[] bytes = "MY STRING OF DOOM!".getBytes();
HttpPost request = new HttpPost();
ByteArrayRequestBody body = new ByteArrayRequestBody(bytes, "contentType");
body.applyTo(new ServerDriverHttpUriRequest(request));
assertThat(IOUtils.toString(request.getEntity().getContent()), is("MY STRING OF DOOM!"));
assertThat(request.getEntity().getContentType().getValue(), is("contentType"));
assertThat(request.getFirstHeader("Content-type").getValue(), is("contentType"));
}Example 100
| Project: restfiddle-master File: PostHandler.java View source code |
public RfResponseDTO process(RfRequestDTO rfRequestDTO) throws IOException {
RfResponseDTO response = null;
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(rfRequestDTO.getEvaluatedApiUrl());
httpPost.addHeader("Content-Type", "application/json");
httpPost.setEntity(new StringEntity(rfRequestDTO.getApiBody()));
try {
response = processHttpRequest(httpPost, httpclient);
} finally {
httpclient.close();
}
return response;
}Example 101
| Project: robolectric-master File: ParamsParserTest.java View source code |
@Test
public void parseParams_shouldParsePostEntitiesIntoParams() throws Exception {
HttpPost post = new HttpPost("example.com");
StringEntity entity = new StringEntity("param1=foobar");
entity.setContentType("application/x-www-form-urlencoded");
post.setEntity(entity);
Map<String, String> params = ParamsParser.parseParams(post);
assertThat("foobar").isEqualTo(params.get("param1"));
}