org.apache.http.impl.client.DefaultHttpClient#execute()源码实例Demo

下面列出了org.apache.http.impl.client.DefaultHttpClient#execute() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: BigApp_Discuz_Android   文件: HttpClientUtils.java
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;
}
 
源代码2 项目: product-ei   文件: ActivitiRestClient.java
/**
 * 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");
}
 
源代码3 项目: NNAnalytics   文件: TestWithMiniClusterBase.java
@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.
    }
  }
}
 
源代码4 项目: java-client-api   文件: ConnectedRESTQA.java
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();
}
 
源代码5 项目: java-client-api   文件: ConnectedRESTQA.java
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();
}
 
源代码6 项目: neembuu-uploader   文件: UGotFileUploaderPlugin.java
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");
    }
}
 
源代码7 项目: java-client-api   文件: TestServerBootstrapper.java
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());
}
 
源代码8 项目: java-client-api   文件: QBFailover.java
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;
	}
}
 
源代码9 项目: candybean   文件: AppiumIosTest.java
@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();
}
 
源代码10 项目: BotLibre   文件: Utils.java
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);
}
 
源代码11 项目: aliyun-cupid-sdk   文件: WebProxyCall.java
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);
    }
}
 
源代码12 项目: java-client-api   文件: TestServerBootstrapper.java
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);
  }
 
源代码13 项目: product-ei   文件: APIHeadMethod.java
@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);
}
 
源代码14 项目: AndroidRobot   文件: HttpClientUtil.java
/** 
 * 获取图片的字节数组 
 *  
 * @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;  
}
 
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);
    }
}
 
源代码16 项目: bateman   文件: QuoteFetcher.java
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;
}
 
@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());
}
 
源代码18 项目: PressureNet-SDK   文件: CbApi.java
@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;
}
 
源代码19 项目: java-client-api   文件: ConnectedRESTQA.java
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();
}
 
源代码20 项目: android-discourse   文件: UrlImageGetter.java
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();
}