下面列出了org.apache.http.impl.client.DefaultHttpClient#execute() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
/**
* 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");
}
@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.
}
}
}
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();
}
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();
}
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");
}
}
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());
}
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;
}
}
@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();
}
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);
}
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);
}
}
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);
}
@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);
}
/**
* 获取图片的字节数组
*
* @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);
}
}
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());
}
@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;
}
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();
}
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();
}