Java Code Examples for org.apache.http.impl.client.DefaultHttpClient#execute()

The following examples show how to use org.apache.http.impl.client.DefaultHttpClient#execute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: QBFailover.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
private boolean isRunning(String host) {
	try {

		DefaultHttpClient client = new DefaultHttpClient();
		client.getCredentialsProvider().setCredentials(new AuthScope(host, 7997),
				new UsernamePasswordCredentials("admin", "admin"));

		HttpGet get = new HttpGet("http://" + host + ":7997?format=json");
		HttpResponse response = client.execute(get);
		ResponseHandler<String> handler = new BasicResponseHandler();
		String body = handler.handleResponse(response);
		if (body.toLowerCase().contains("healthy")) {
			return true;
		} else {
			return false;
		}

	} catch (Exception e) {
		return false;
	}
}
 
Example 2
Source File: TestServerBootstrapper.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
private void invokeBootstrapExtension() throws ClientProtocolException, IOException {
  final String params = Common.BALANCED ? "?rs%3Abalanced=true" : "";

  DefaultHttpClient client = new DefaultHttpClient();

  client.getCredentialsProvider().setCredentials(
    new AuthScope(host, port),
    new UsernamePasswordCredentials(username, password));

  HttpPost post = new HttpPost("http://" + host + ":" + port
    + "/v1/resources/bootstrap" + params);

  HttpResponse response = client.execute(post);
  @SuppressWarnings("unused")
  HttpEntity entity = response.getEntity();
  System.out.println("Invoked bootstrap extension.  Response is "
    + response.toString());
}
 
Example 3
Source File: HttpClientUtils.java    From BigApp_Discuz_Android with Apache License 2.0 6 votes vote down vote up
public static String httpPostWithWCF(String serverUrl, String method,
                                     JSONObject params) {
    String responseStr = null;
    try {
        String url = serverUrl + method;
        DefaultHttpClient client = new DefaultHttpClient();

        HttpPost request = new HttpPost(url);

        request.setEntity(new StringEntity(params.toString(), CODE));
        request.setHeader(HTTP.CONTENT_TYPE, "text/json");

        HttpResponse response = client.execute(request);

        responseStr = EntityUtils.toString(response.getEntity(), CODE);
        // System.out.println("responseStr:" + responseStr);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return responseStr;
}
 
Example 4
Source File: UGotFileUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 6 votes vote down vote up
public static void loginUGotFile() 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 ugotfile.com");
    HttpPost httppost = new HttpPost("http://ugotfile.com/user/login");
    httppost.setHeader("Cookie", phpsessioncookie);
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("ugfLoginUserName", ""));
    formparams.add(new BasicNameValuePair("ugfLoginPassword", ""));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    httppost.setEntity(entity);
    HttpResponse httpresponse = httpclient.execute(httppost);
    HttpEntity resEntity = httpresponse.getEntity();
    if (httpresponse.getStatusLine().toString().contains("302")) {
        tmp = httpresponse.getLastHeader("Location").getValue();
        System.out.println("UGotFile Login success");
    } else {
        System.out.println("UGotFile login failed");
    }
}
 
Example 5
Source File: ActivitiRestClient.java    From product-ei with Apache License 2.0 6 votes vote down vote up
/**
 * Method use to instantiate a process instance using the definition ID
 *
 * @param processDefintionID used to start a processInstance
 * @throws IOException
 * @throws JSONException
 * @returns String Array which contains status and processInstanceID
 */
public String[] startProcessInstanceByDefintionID(String processDefintionID)
        throws IOException, JSONException, RestClientException {
    String url = serviceURL + "runtime/process-instances";
    DefaultHttpClient httpClient = getHttpClient();
    HttpPost httpPost = new HttpPost(url);
    StringEntity params = new StringEntity("{\"processDefinitionId\":\""
                                           + processDefintionID + "\"}",
                                           ContentType.APPLICATION_JSON);
    httpPost.setEntity(params);
    HttpResponse response = httpClient.execute(httpPost);
    String status = response.getStatusLine().toString();
    String responseData = EntityUtils.toString(response.getEntity());
    JSONObject jsonResponseObject = new JSONObject(responseData);
    if (status.contains(Integer.toString(HttpStatus.SC_CREATED)) || status.contains(Integer.toString(HttpStatus.SC_OK))) {
        String processInstanceID = jsonResponseObject.getString(ID);
        return new String[]{status, processInstanceID};
    }
    throw new RestClientException("Cannot Find Process Instance");
}
 
Example 6
Source File: ConnectedRESTQA.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
private static void setRESTServerWithDistributeTimestamps(String restServerName, String distributeTimestampType) throws Exception {
 DefaultHttpClient client = new DefaultHttpClient();

 client.getCredentialsProvider().setCredentials(new AuthScope(host_name, getAdminPort()),
	  new UsernamePasswordCredentials("admin", "admin"));
 String extSecurityrName = "";
 String body = "{\"group-name\": \"Default\",\"distribute-timestamps\": \"" + distributeTimestampType + "\"}";
 ;

 HttpPut put = new HttpPut("http://" + host_name + ":" + admin_port + "/manage/v2/servers/" + restServerName
	  + "/properties?server-type=http");
 put.addHeader("Content-type", "application/json");
 put.setEntity(new StringEntity(body));

 HttpResponse response2 = client.execute(put);
 HttpEntity respEntity = response2.getEntity();
 if (respEntity != null) {
  String content = EntityUtils.toString(respEntity);
  System.out.println(content);
 }
 client.getConnectionManager().shutdown();
}
 
Example 7
Source File: ConnectedRESTQA.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
public static void associateRESTServerWithDigestAuth(String restServerName) throws Exception {
	DefaultHttpClient client = new DefaultHttpClient();

	client.getCredentialsProvider().setCredentials(new AuthScope(host_name, getAdminPort()),
			new UsernamePasswordCredentials("admin", "admin"));
	String extSecurityrName = "";
	String body = "{\"group-name\": \"Default\", \"authentication\":\"Digest\",\"internal-security\": \"true\",\"external-security\": \""
			+ extSecurityrName + "\"}";
	;

	HttpPut put = new HttpPut("http://" + host_name + ":" + admin_port + "/manage/v2/servers/" + restServerName
			+ "/properties?server-type=http");
	put.addHeader("Content-type", "application/json");
	put.setEntity(new StringEntity(body));

	HttpResponse response2 = client.execute(put);
	HttpEntity respEntity = response2.getEntity();
	if (respEntity != null) {
		String content = EntityUtils.toString(respEntity);
		System.out.println(content);
	}
	client.getConnectionManager().shutdown();
}
 
Example 8
Source File: TestWithMiniClusterBase.java    From NNAnalytics with Apache License 2.0 6 votes vote down vote up
@Before
public void before() {
  client = new DefaultHttpClient();

  boolean isServingQueries = false;
  while (!isServingQueries) {
    try {
      HttpGet get = new HttpGet("http://localhost:4567/info");
      HttpResponse res = client.execute(hostPort, get);
      String body = IOUtils.toString(res.getEntity().getContent());
      if (body.contains("Ready to service queries: true")) {
        isServingQueries = true;
      } else {
        Thread.sleep(1000L);
      }
    } catch (Exception ex) {
      // Do nothing.
    }
  }
}
 
Example 9
Source File: HttpClientUtil.java    From AndroidRobot with Apache License 2.0 5 votes vote down vote up
/** 
 * 获取图片的字节数组 
 *  
 * @createTime 2011-11-24 
 * @param url 
 * @return 
 * @throws IOException 
 * @throws ClientProtocolException 
 * @throws ClientProtocolException 
 * @throws IOException 
 */  
public static byte[] getImg(String url) throws ClientProtocolException,  
        IOException {  
    byte[] bytes = null;  
    // 创建HttpClient实例  
    DefaultHttpClient httpclient = getDefaultHttpClient(CHARSET_ENCODING);  
    // 获取url里面的信息  
    HttpGet hg = new HttpGet(url);  
    HttpResponse hr = httpclient.execute(hg);  
    bytes = EntityUtils.toByteArray(hr.getEntity());  
    // 转换内容为字节  
    return bytes;  
}
 
Example 10
Source File: CookieHeaderExpiresHavingCommaTestCase.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@Test(groups = "wso2.esb",
      description = "Test SetCookieHeader With Expires having a comma")
public void testSetCookieHeaderWithExpires() throws IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(getApiInvocationURL("cookieHeaderTestAPI"));
    HttpResponse httpResponse = httpclient.execute(httpGet);
    Assert.assertEquals(httpResponse.getStatusLine().getStatusCode(), 200,
            "Request failed. Response received is : " + httpResponse.toString());
}
 
Example 11
Source File: QuoteFetcher.java    From bateman with MIT License 5 votes vote down vote up
protected String fetchURLasString(String url) throws IOException, ParseException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    HttpResponse response = httpclient.execute(httpGet);
    HttpEntity entity = response.getEntity();
    String body = EntityUtils.toString(entity);
    EntityUtils.consume(entity);
    httpGet.releaseConnection();
    return body;
}
 
Example 12
Source File: MultiUploadUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
private static void fileUpload() throws IOException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    System.out.println(postURL);
    System.out.println(ucookie);
    System.out.println(uid);
    HttpPost httppost = new HttpPost(postURL);
    httppost.setHeader("Cookie", ucookie);
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    File f = new File("h:/Rock Lee.jpg");
    reqEntity.addPart("UPLOAD_IDENTIFIER", new StringBody(uid));
    reqEntity.addPart("u", new StringBody(ucookie));
    FileBody bin = new FileBody(f);
    reqEntity.addPart("file_0", bin);
    reqEntity.addPart("service_1", new StringBody("1"));
    reqEntity.addPart("service_16", new StringBody("1"));
    reqEntity.addPart("service_7", new StringBody("1"));
    reqEntity.addPart("service_17", new StringBody("1"));
    reqEntity.addPart("service_9", new StringBody("1"));
    reqEntity.addPart("service_10", new StringBody("1"));
    reqEntity.addPart("remember_1", new StringBody("1"));
    reqEntity.addPart("remember_16", new StringBody("1"));
    reqEntity.addPart("remember_7", new StringBody("1"));
    reqEntity.addPart("remember_17", new StringBody("1"));
    reqEntity.addPart("remember_9", new StringBody("1"));
    reqEntity.addPart("remember_10", new StringBody("1"));
    httppost.setEntity(reqEntity);
    System.out.println("Now uploading your file into multiupload.com. Please wait......................");
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    if (resEntity != null) {
        uploadresponse = EntityUtils.toString(resEntity);
        System.out.println("Response :\n" + uploadresponse);
        uploadresponse = parseResponse(uploadresponse, "\"downloadid\":\"", "\"");
        downloadlink = "http://www.multiupload.com/" + uploadresponse;
        System.out.println("Download link : " + downloadlink);
    }
}
 
Example 13
Source File: AppiumIosTest.java    From candybean with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testSessions() throws Exception {
    HttpGet request = new HttpGet("http://localhost:4723/wd/hub/sessions");
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(request);
    HttpEntity entity = response.getEntity();
    JSONObject jsonObject = (JSONObject) new JSONParser().parse(EntityUtils.toString(entity));
    String sessionId = ((RemoteWebDriver) driver).getSessionId().toString();
    assertEquals(sessionId, jsonObject.get("sessionId"));
    httpClient.close();
}
 
Example 14
Source File: APIHeadMethod.java    From product-ei with Apache License 2.0 5 votes vote down vote up
@Test(groups = "wso2.esb", description = "API HTTP HEAD Method" )
public void apiHTTPHeadMethodTest() throws Exception {
    String restURL = "http://localhost:8480/headTest";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpHead httpHead = new HttpHead(restURL);
    HttpResponse response = httpclient.execute(httpHead);

    Assert.assertTrue(stringExistsInLog("API_HIT"));

    // http head method should return a 200 OK
    assertTrue(response.getStatusLine().getStatusCode() == 200);
    // it should not contain a message body
    assertTrue(response.getEntity() == null);
}
 
Example 15
Source File: TestServerBootstrapper.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
private void deleteRestServer() throws ClientProtocolException, IOException {

    DefaultHttpClient client = new DefaultHttpClient();

    client.getCredentialsProvider().setCredentials(
      new AuthScope(host, 8002),
      new UsernamePasswordCredentials(username, password));

    HttpDelete delete = new HttpDelete(
      "http://"
        + host
        + ":8002/v1/rest-apis/java-unittest?include=modules&include=content");

    client.execute(delete);
  }
 
Example 16
Source File: WebProxyCall.java    From aliyun-cupid-sdk with Apache License 2.0 5 votes vote down vote up
public void callWebProxy(String url) {
    String resultCode = "";
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        HttpGet httpget = new HttpGet(url);
        HttpResponse response = httpclient.execute(httpget);

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            resultCode = ResponseCode.CALLRESPONSEERROR;
            if (entity != null) {
                String responseString = EntityUtils.toString(entity);
                if (responseString.contains("Spark Jobs") && responseString.contains("Stages")
                        && responseString.contains("Storage") && responseString.contains("Environment")
                        && responseString.contains("Executors")) {
                    resultCode = ResponseCode.CALLSUCCESS;
                }
            }
        } else if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                || statusCode == HttpStatus.SC_MOVED_PERMANENTLY) {
            resultCode = ResponseCode.CALLFORBIDDEN;
        } else {
            resultCode = ResponseCode.OTHER_RESPONSE + String.valueOf(statusCode);
        }
    } catch (Exception e) {
        LOG.warn("WebProxyCall exception " + e.getMessage());
        resultCode = ResponseCode.CALLEXCEPTION;
    } finally {
        httpclient.close();
    }
    LOG.info("WebProxyCall result " + resultCode);
    if (!resultCode.equals(ResponseCode.CALLSUCCESS)) {
        System.exit(1);
    }
}
 
Example 17
Source File: Utils.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
public static String httpPUT(String url, String type, String data) throws Exception {
	HttpPut request = new HttpPut(url);
       StringEntity params = new StringEntity(data, "utf-8");
       request.addHeader("content-type", type);
       request.setEntity(params);
	DefaultHttpClient client = new DefaultHttpClient();
       HttpResponse response = client.execute(request);
	return fetchResponse(response);
}
 
Example 18
Source File: UrlImageGetter.java    From android-discourse with Apache License 2.0 4 votes vote down vote up
private InputStream fetch(String urlString) throws MalformedURLException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet request = new HttpGet(urlString);
    HttpResponse response = httpClient.execute(request);
    return response.getEntity().getContent();
}
 
Example 19
Source File: ConnectedRESTQA.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
public static void addElementRangeIndexTemporalAxis(String dbName, String axisName, String namespaceStart,
		String localnameStart, String namespaceEnd, String localnameEnd) throws Exception {
	/**
	 * { "axis-name": "eri-json-system", "axis-start": {
	 * "element-reference": { "namespace-uri": "", "localname":
	 * "eri-system-start", "scalar-type": "dateTime" } }, "axis-end": {
	 * "element-reference": { "namespace-uri": "", "localname":
	 * "eri-system-end", "scalar-type": "dateTime" } } }
	 */
	ObjectMapper mapper = new ObjectMapper();
	ObjectNode rootNode = mapper.createObjectNode();

	rootNode.put("axis-name", axisName);

	// Set axis start
	ObjectNode axisStart = mapper.createObjectNode();
	ObjectNode elementReferenceStart = mapper.createObjectNode();
	elementReferenceStart.put("namespace-uri", namespaceStart);
	elementReferenceStart.put("localname", localnameStart);
	elementReferenceStart.put("scalar-type", "dateTime");

	axisStart.set("element-reference", elementReferenceStart);
	rootNode.set("axis-start", axisStart);

	// Set axis end
	ObjectNode axisEnd = mapper.createObjectNode();
	ObjectNode elementReferenceEnd = mapper.createObjectNode();
	elementReferenceEnd.put("namespace-uri", namespaceStart);
	elementReferenceEnd.put("localname", localnameEnd);
	elementReferenceEnd.put("scalar-type", "dateTime");

	axisEnd.set("element-reference", elementReferenceEnd);
	rootNode.set("axis-end", axisEnd);

	System.out.println(rootNode.toString());

	DefaultHttpClient client = new DefaultHttpClient();
	client.getCredentialsProvider().setCredentials(new AuthScope(host_name, getAdminPort()),
			new UsernamePasswordCredentials("admin", "admin"));

	HttpPost post = new HttpPost("http://" + host_name + ":" + admin_port + "/manage/v2/databases/" + dbName
			+ "/temporal/axes?format=json");

	post.addHeader("Content-type", "application/json");
	post.addHeader("accept", "application/json");
	post.setEntity(new StringEntity(rootNode.toString()));

	HttpResponse response = client.execute(post);
	HttpEntity respEntity = response.getEntity();
	if (response.getStatusLine().getStatusCode() == 400) {
		HttpEntity entity = response.getEntity();
		String responseString = EntityUtils.toString(entity, "UTF-8");
		System.out.println(responseString);
	} else if (respEntity != null) {
		// EntityUtils to get the response content
		String content = EntityUtils.toString(respEntity);
		System.out.println(content);

		System.out.println("Temporal axis: " + axisName + " created");
		System.out.println("==============================================================");
	} else {
		System.out.println("No Proper Response");
	}
	client.getConnectionManager().shutdown();
}
 
Example 20
Source File: CbApi.java    From PressureNet-SDK with MIT License 4 votes vote down vote up
@Override
protected String doInBackground(String... params) {
	String responseText = "";
	try {
		DefaultHttpClient client = new DefaultHttpClient();
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("min_latitude", apiCall
				.getMinLatitude() + "" + ""));
		nvps.add(new BasicNameValuePair("max_latitude", apiCall
				.getMaxLatitude() + "" + ""));
		nvps.add(new BasicNameValuePair("min_longitude", apiCall
				.getMinLongitude() + "" + ""));
		nvps.add(new BasicNameValuePair("max_longitude", apiCall
				.getMaxLongitude() + "" + ""));
		nvps.add(new BasicNameValuePair("start_time", apiCall
				.getStartTime() + ""));
		nvps.add(new BasicNameValuePair("end_time", apiCall
				.getEndTime() + ""));
		nvps.add(new BasicNameValuePair("log_duration", apiCall.getLogDuration()));

		String paramString = URLEncodedUtils.format(nvps, "utf-8");

		String serverURL = apiStatsServerURL;

		serverURL = serverURL + paramString;
		
		log("cbservice api sending " + serverURL);
		HttpGet get = new HttpGet(serverURL);
		// Execute the GET call and obtain the response
		HttpResponse getResponse = client.execute(get);
		HttpEntity responseEntity = getResponse.getEntity()	;
		log("stats response " + responseEntity.getContentLength());

		BufferedReader r = new BufferedReader(new InputStreamReader(
				responseEntity.getContent()));

		StringBuilder total = new StringBuilder();
		String line;
		if (r != null) {
			while ((line = r.readLine()) != null) {
				total.append(line);
			}
			responseText = total.toString();
		}
	} catch (Exception e) {
		//System.out.println("api error");
		e.printStackTrace();
	}
	return responseText;
}