public synchronized void updateHtmlEntry(String key, String html) throws HttpException { HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(catalogDbURL + "update"); System.err.println(key); postMethod.addParameter("key", key); postMethod.addParameter("columns", html); try { httpClient.executeMethod(postMethod); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (postMethod.getStatusCode() == HttpStatus.SC_OK) { try { String resp = postMethod.getResponseBodyAsString(); System.err.println(resp); } catch (IOException e) { e.printStackTrace(); } } else { throw new HttpException("failed to post form."); } }
public String mediaCreate(File f, DCArray assets_names, DCObject meta) throws Exception { String upload_url = this.fileUpload(); PostMethod filePost = null; try { filePost = new PostMethod(upload_url); Part[] parts = {new FilePart("file", f)}; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status == HttpStatus.SC_OK) { ObjectMapper mapper = new ObjectMapper(); DCObject json_response = DCObject.create(mapper.readValue(filePost.getResponseBodyAsString(), Map.class)); return this.mediaCreate(json_response.pull("url"), assets_names, meta); } else { throw new DCException("Upload failed."); } } catch (Exception e) { throw new DCException("Upload failed: " + e.getMessage()); } finally { if (filePost != null) { filePost.releaseConnection(); } } }
/** * 批量上传图片 * * @param path 服务器地址 * @param name 用户名 * @param filePath sd卡图片路径 * @param onSuccessListner * @return * @throws Exception */ public static String sendDataByHttpClientPost( String path, List<File> files, List<Part> mparameters, OnSuccessListner listner) throws Exception { for (int i = 0; i < files.size(); i++) { mparameters.add(new FilePart("file", files.get(i))); } Part[] parts = mparameters.toArray(new Part[0]); PostMethod filePost = new PostMethod(path); filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); if (status == 200) { Log.e("DataService", "" + filePost.getResponseCharSet()); String result = new String(filePost.getResponseBodyAsString()); Log.e("DataService", "--" + result); // JSONArray array = (JSONArray) JSON.parse(result); Log.e("JSONArray", "--" + result); listner.onSuccess(result); return result; } else { listner.onFailed(); return null; } }
// http post public static String httpPost(String url, String body) throws Exception { ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory(); Protocol.registerProtocol("https", new Protocol("https", fcty, 443)); PostMethod post = new PostMethod(url); post.setRequestBody(body); // 这里添加xml字符串 // 指定请求内容的类型 post.setRequestHeader("Content-type", "application/json; charset=utf-8"); HttpClient httpclient = new HttpClient(); // 创建 HttpClient 的实例 httpclient.executeMethod(post); String res = post.getResponseBodyAsString(); logger.info(res); post.releaseConnection(); // 释放连接 if (res.indexOf("40001") > -1) { getFreshAccessToken(); } return res; }
/** * 鍙栧緱ST * * @param server * @param ticketGrantingTicket * @param service */ private static String getServiceTicket( final String server, final String ticketGrantingTicket, final String service) { if (ticketGrantingTicket == null) return null; final HttpClient client = new HttpClient(); final PostMethod post = new PostMethod(server + "/" + ticketGrantingTicket); post.setRequestBody(new NameValuePair[] {new NameValuePair("service", service)}); try { client.executeMethod(post); final String response = post.getResponseBodyAsString(); switch (post.getStatusCode()) { case 200: return response; default: warning("Invalid response code (" + post.getStatusCode() + ") from CAS server!"); info("Response (1k): " + response.substring(0, Math.min(1024, response.length()))); break; } } catch (final IOException e) { warning(e.getMessage()); } finally { post.releaseConnection(); } return null; }
public FormValidation validate() throws IOException { HttpClient hc = createClient(); PostMethod post = new PostMethod(url + "Login"); post.addParameter("userName", getUsername()); if (getPassword() != null) { // post.addParameter("password",getPassword()); post.addParameter("password", getPassword().getPlainText()); } else { post.addParameter("password", ""); } hc.executeMethod(post); // if the login succeeds, we'll see a redirect Header loc = post.getResponseHeader("Location"); if (loc != null && loc.getValue().endsWith("/Central")) return FormValidation.ok("Success!"); if (!post.getResponseBodyAsString().contains("SOASTA")) return FormValidation.error(getUrl() + " doesn't look like a CloudTest server"); // if it fails, the server responds with 200! return FormValidation.error("Invalid credentials."); }
/** * 执行一个HTTP POST 请求,返回请求响应的HTML * * @param url 请求的URL 地址 * @param params 请求的查询参数,可以为null * @return 返回请求响应的HTML */ private static String doPost(String url, Map<String, String> params) { String response = null; HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(url); postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8"); // 设置Post 数据 if (!params.isEmpty()) { int i = 0; NameValuePair[] data = new NameValuePair[params.size()]; for (Entry<String, String> entry : params.entrySet()) { data[i] = new NameValuePair(entry.getKey(), entry.getValue()); i++; } postMethod.setRequestBody(data); } try { client.executeMethod(postMethod); if (postMethod.getStatusCode() == HttpStatus.SC_OK) { response = postMethod.getResponseBodyAsString(); } } catch (Exception e) { e.printStackTrace(); } finally { postMethod.releaseConnection(); } return response; }
public static void send(String content, String mobile) throws Exception { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(Url); client.getParams().setContentCharset("UTF-8"); method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8"); NameValuePair[] data = { // 提交短信 new NameValuePair("account", "cf_ddz"), new NameValuePair("password", "zaq12wsx"), // 密码可以使用明文密码或使用32位MD5加密 new NameValuePair("mobile", mobile), new NameValuePair("content", content), }; method.setRequestBody(data); client.executeMethod(method); String SubmitResult = method.getResponseBodyAsString(); Document doc = DocumentHelper.parseText(SubmitResult); Element root = doc.getRootElement(); String code = root.elementText("code"); String msg = root.elementText("msg"); String smsid = root.elementText("smsid"); logger.info(code + "|" + msg + "|" + smsid); }
private static boolean createRepo( final String scmUrl, final String password, final String repository) { HttpClient client = new HttpClient(); String uri = scmUrl + API + "/projects"; LOGGER.debug("Create Repo: {}", uri); PostMethod post = new PostMethod(uri); post.setParameter("name", repository); post.setParameter("private_token", password); try { int result = client.executeMethod(post); LOGGER.info("Return code: " + result); for (Header header : post.getResponseHeaders()) { LOGGER.info(header.toString().trim()); } LOGGER.info(post.getResponseBodyAsString()); } catch (HttpException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } finally { post.releaseConnection(); } return true; }
private HttpClient login(PostMethod method) throws Exception { if (method.getHostConfiguration().getProtocol() == null) { throw new Exception("Protocol not specified"); } HttpClient client = getHttpClient(); client .getState() .setCredentials( AuthScope.ANY, new UsernamePasswordCredentials(getUsername(), getPassword())); configureHttpMethod(method); method.addParameter("login", getUsername()); method.addParameter("password", getPassword()); client.getParams().setContentCharset("UTF-8"); client.executeMethod(method); if (method.getStatusCode() != 200) { throw new Exception("Cannot login: HTTP status code " + method.getStatusCode()); } String response = method.getResponseBodyAsString(1000); if (response == null) { throw new NullPointerException(); } if (!response.contains("<login>ok</login>")) { int pos = response.indexOf("</error>"); int length = "<error>".length(); if (pos > length) { response = response.substring(length, pos); } throw new Exception("Cannot login: " + response); } return client; }
public String getContextByPostMethod(String url, List<KeyValue> params) { HttpClient client = getHttpClient(); client.getParams().setParameter("http.protocol.content-charset", this.codeing); PostMethod post = null; String result = ""; try { URL u = new URL(url); client .getHostConfiguration() .setHost( u.getHost(), u.getPort() == -1 ? u.getDefaultPort() : u.getPort(), u.getProtocol()); post = new PostMethod(u.getPath()); NameValuePair[] nvps = new NameValuePair[params.size()]; int i = 0; for (KeyValue kv : params) { nvps[i] = new NameValuePair(kv.getKey(), kv.getValue()); i++; } post.setRequestBody(nvps); client.executeMethod(post); result = post.getResponseBodyAsString(); } catch (Exception e) { throw new NetException("HttpClient catch!", e); } finally { if (post != null) post.releaseConnection(); } return result; }
public String refreshToken(String refresh_token){ String response = null; String Client_id = AppConfig.APP_ID; String Client_secret = AppConfig.APP_SECRET; String Url = "https://graph.renren.com/oauth/token?"+ "grant_type=refresh_token&"+ "refresh_token="+refresh_token+"&"+ "client_id="+Client_id+"&"+ "client_secret="+Client_secret; HttpClient client = new HttpClient(); PostMethod method = new PostMethod (Url); try{ client.executeMethod(method); if(method.getStatusCode()== HttpStatus.SC_OK){ response = method.getResponseBodyAsString(); } }catch (IOException e) { // TODO: handle exception System.out.println("Exception happend when processing Http Post:"+Url+"\n"+e); }finally{ method.releaseConnection(); } System.out.println("[FeedStub : run]"+response); net.sf.json.JSONArray jsonarray = net.sf.json.JSONArray.fromObject(response); net.sf.json.JSONObject jsonobject = jsonarray.getJSONObject(0); return (String) jsonobject.get("access_token"); }
public static String executePost(final String host, final String path, final List<Part> parts) throws Exception { final HttpClient client = new HttpClient(); client.getParams().setParameter("http.protocol.single-cookie-header", true); client .getParams() .setParameter( "http.useragent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)"); final HttpState httpState = new HttpState(); final HostConfiguration hostConfiguration = new HostConfiguration(); // add the proxy HttpProxy.addProxy(hostConfiguration); hostConfiguration.setHost(host); final MultipartRequestEntity entity = new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), new HttpMethodParams()); final PostMethod post = new PostMethod(getHostUrlPrefix(host) + path); post.setRequestEntity(entity); try { final int status = client.executeMethod(hostConfiguration, post, httpState); if (status != 200) { throw new Exception( "Post command to " + host + " failed, the server returned status: " + status); } return post.getResponseBodyAsString(); } finally { post.releaseConnection(); } }
private String getEditorResponse(String urlpath, String encProcessSrc) { HttpClient httpclient = new HttpClient(); PostMethod authMethod = new PostMethod(urlpath); NameValuePair[] data = { new NameValuePair("j_username", "admin"), new NameValuePair("j_password", "admin") }; authMethod.setRequestBody(data); try { httpclient.executeMethod(authMethod); } catch (IOException e) { e.printStackTrace(); return null; } finally { authMethod.releaseConnection(); } PostMethod theMethod = new PostMethod(urlpath); theMethod.setParameter("processsource", encProcessSrc); StringBuffer sb = new StringBuffer(); try { httpclient.executeMethod(theMethod); sb.append(theMethod.getResponseBodyAsString()); return sb.toString(); } catch (Exception e) { e.printStackTrace(); return null; } finally { theMethod.releaseConnection(); } }
/** * 单次上传图片or文件 * * @param path * @param name * @param filePath * @return * @throws Exception */ public static String sendDataByHttpClientPost(String path, String name, String filePath) throws Exception { /* * List<Part> partList = new ArrayList<Part>(); partList.add(new * StringPart("user", name)); * * for (int i = 0; i < 4; i++) { partList.add(new FilePart(name, * FilePart())); } */ // 实例化上传数据的数组 Part[] parts = {new StringPart("user", name), new FilePart("file", new File(filePath))}; PostMethod filePost = new PostMethod(path); filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); int status = client.executeMethod(filePost); Log.e("Other", "返回结果:" + status); if (status == 200) { System.out.println(filePost.getResponseCharSet()); String result = new String(filePost.getResponseBodyAsString()); System.out.println("--" + result); return result; } else { throw new IllegalStateException("服务器状态异常"); } }
@Action("SignModeCheck") public String signModeCheck() throws Exception { try { HttpClient client = new HttpClient(); String url = "http://127.0.0.1:" + getServerPort() + "/service/"; logger.debug("url: " + url); CommunicationVo requestVo = new CommunicationVo(); requestVo.setTradeCode("000001"); requestVo.putParam("signMode", this.signVo.getSignMode()); requestVo.putParam("certDn", this.signVo.getCertDn()); PostMethod postMethod = new PostMethod(url); postMethod.addParameter("json", requestVo.toJson()); client.executeMethod(postMethod); String resp = postMethod.getResponseBodyAsString().trim(); postMethod.releaseConnection(); logger.info("resp: " + resp); CommunicationVo respVo = CommunicationVo.getInstancefromJson(resp); if (!"0000".equals(respVo.getStatus())) { throw new ServiceException(respVo.getMessage()); } this.dwzResp.ajaxSuccessForward(respVo.getMessage()); this.dwzResp.setAlertClose(Boolean.valueOf(false)); } catch (Exception e) { logger.error(ExceptionUtils.getStackTrace(e)); this.dwzResp.errorForward(e.getMessage()); return "dwz"; } return "dwz"; }
/** Test that the body consisting of a file part can be posted. */ public void testPostFilePart() throws Exception { this.server.setHttpService(new EchoService()); PostMethod method = new PostMethod(); byte[] content = "Hello".getBytes(); MultipartRequestEntity entity = new MultipartRequestEntity( new Part[] { new FilePart( "param1", new ByteArrayPartSource("filename.txt", content), "text/plain", "ISO-8859-1") }, method.getParams()); method.setRequestEntity(entity); client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertTrue( body.indexOf("Content-Disposition: form-data; name=\"param1\"; filename=\"filename.txt\"") >= 0); assertTrue(body.indexOf("Content-Type: text/plain; charset=ISO-8859-1") >= 0); assertTrue(body.indexOf("Content-Transfer-Encoding: binary") >= 0); assertTrue(body.indexOf("Hello") >= 0); }
public static void fetchNextPage(Integer pageNo, HttpClient client) throws Exception { NameValuePair[] data = { new NameValuePair( "User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:25.0) Gecko/20100101 Firefox/25.0"), new NameValuePair("__EVENTARGUMENT", ""), new NameValuePair("__EVENTTARGET", ""), new NameValuePair("__VIEWSTATE", viewState), new NameValuePair("__EVENTVALIDATION", eventValidation), new NameValuePair("ctl00%24ContentPlaceHolder1%24ImplementDayDDList", "0"), new NameValuePair("ctl00%24ContentPlaceHolder1%24ImplementMonthDDList", "0"), new NameValuePair("ctl00%24ContentPlaceHolder1%24PropertyDDL", "2"), new NameValuePair("ctl00%24ContentPlaceHolder1%24PublishedDayDDList", "0"), new NameValuePair("ctl00%24ContentPlaceHolder1%24PublishedMonthDDList", "0"), new NameValuePair("ctl00$ContentPlaceHolder1$btnNext.x", btn_x), new NameValuePair("ctl00$ContentPlaceHolder1$btnNext.y", btn_y), new NameValuePair("ctl00%24ContentPlaceHolder1%24pageNo", ""), new NameValuePair("ctl00%24ContentPlaceHolder1%24statusDDList", "2"), new NameValuePair( "ctl00_ContentPlaceHolder1_categoryTreeView_ExpandState", "enennnnnnnnnnnnnnnnnnnnnnnnnnnn") }; PostMethod post = new PostMethod("http://www.catarc.org.cn/standard/SearchStandard.aspx"); post.setRequestBody(data); client.executeMethod(post); String html = post.getResponseBodyAsString(); setViewState(html); setEventValidation(html); setStandardIdsToMap(pageNo, html); }
private void doPost( String realm, String host, String user, String pass, String url, boolean handshake, boolean preemtive, int result) throws Exception { HttpClient client = new HttpClient(); client.getParams().setAuthenticationPreemptive(preemtive); client .getState() .setCredentials( new AuthScope(host, -1, realm), new UsernamePasswordCredentials(user, pass)); PostMethod post = new PostMethod(url); post.setDoAuthentication(handshake); StringRequestEntity requestEntity = new StringRequestEntity(soapRequest, "text/xml", "UTF-8"); post.setRequestEntity(requestEntity); try { int status = client.executeMethod(post); assertEquals(result, status); assertNotNull(post.getResponseBodyAsString()); } finally { post.releaseConnection(); } }
private static String login() throws Exception { HttpClient httpClient = new HttpClient(); PostMethod loginMethod = new PostMethod("http://*****:*****@gmail.com"); loginRequest.setPassword("testpass"); JAXBContext context = JAXBContext.newInstance("com.fb.platform.auth._1_0"); Marshaller marshaller = context.createMarshaller(); StringWriter sw = new StringWriter(); marshaller.marshal(loginRequest, sw); StringRequestEntity requestEntity = new StringRequestEntity(sw.toString()); loginMethod.setRequestEntity(requestEntity); int statusCode = httpClient.executeMethod(loginMethod); if (statusCode != HttpStatus.SC_OK) { System.out.println("unable to execute the login method : " + statusCode); return null; } String loginResponseStr = loginMethod.getResponseBodyAsString(); System.out.println("Got the login Response : \n" + loginResponseStr); Unmarshaller unmarshaller = context.createUnmarshaller(); LoginResponse loginResponse = (LoginResponse) unmarshaller.unmarshal(new StreamSource(new StringReader(loginResponseStr))); return loginResponse.getSessionToken(); }
public String POST(String uri, String content) throws IOException { PostMethod method = new PostMethod(url + uri); method.setRequestHeader("Accept", MESSAGE_FORMAT); RequestEntity body = new StringRequestEntity(content, MESSAGE_FORMAT, "UTF-8"); method.setRequestEntity(body); client.executeMethod(method); return method.getResponseBodyAsString(); }
@Test public void testSettingsCreateWithEmptyJson() throws IOException { // Call Create Setting REST API PostMethod post = httpPost("/interpreter/setting/", ""); LOG.info("testSettingCRUD create response\n" + post.getResponseBodyAsString()); assertThat("test create method:", post, isBadRequest()); post.releaseConnection(); }
public Response multPartURL( String url, PostParameter[] params, ImageItem item, boolean authenticated) throws WeiboException { PostMethod post = new PostMethod(url); try { org.apache.commons.httpclient.HttpClient client = getHttpClient(); long t = System.currentTimeMillis(); Part[] parts = null; if (params == null) { parts = new Part[1]; } else { parts = new Part[params.length + 1]; } if (params != null) { int i = 0; for (PostParameter entry : params) { parts[i++] = new StringPart(entry.getName(), (String) entry.getValue()); } parts[parts.length - 1] = new ByteArrayPart(item.getContent(), item.getName(), item.getContentType()); } post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); List<Header> headers = new ArrayList<Header>(); if (authenticated) { if (oauth == null) {} String authorization = null; if (null != oauth) { // use OAuth authorization = oauth.generateAuthorizationHeader("POST", url, params, oauthToken); } else { throw new IllegalStateException( "Neither user ID/password combination nor OAuth consumer key/secret combination supplied"); } headers.add(new Header("Authorization", authorization)); log("Authorization: " + authorization); } client.getHostConfiguration().getParams().setParameter("http.default-headers", headers); client.executeMethod(post); Response response = new Response(); response.setResponseAsString(post.getResponseBodyAsString()); response.setStatusCode(post.getStatusCode()); log( "multPartURL URL:" + url + ", result:" + response + ", time:" + (System.currentTimeMillis() - t)); return response; } catch (Exception ex) { throw new WeiboException(ex.getMessage(), ex, -1); } finally { post.releaseConnection(); } }
public void testHttpPost() throws URISyntaxException, HttpException, IOException { URI uri = new URI(HTTP_LOCALHOST_60198); PostMethod postMethod = new PostMethod(uri.toString()); postMethod.setRequestEntity(new StringRequestEntity(TEST_MESSAGE)); HttpConnection cnn = new HttpConnection(uri.getHost(), uri.getPort()); cnn.open(); postMethod.execute(new HttpState(), cnn); System.out.println("PostResponse: " + postMethod.getResponseBodyAsString()); }
public AccessTokenInfo getAccessToken(String username, String password, String appInstanceId) throws AccessTokenException { SSLContext ctx; String response = ""; try { ctx = SSLContext.getInstance("TLS"); ctx.init( new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom()); SSLContext.setDefault(ctx); URL url = new URL(tokenURL); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setHostnameVerifier( new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); // System.out.println(conn.getResponseCode()); conn.disconnect(); HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(tokenURL); postMethod.addParameter(new NameValuePair("grant_type", grantType)); postMethod.addParameter(new NameValuePair("username", username)); postMethod.addParameter(new NameValuePair("password", password)); postMethod.addParameter(new NameValuePair("scope", scope + appInstanceId)); postMethod.addRequestHeader("Authorization", "Basic " + appToken); postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); httpClient.executeMethod(postMethod); response = postMethod.getResponseBodyAsString(); log.info(response); JSONObject jsonObject = new JSONObject(response); AccessTokenInfo accessTokenInfo = new AccessTokenInfo(); accessTokenInfo.setAccess_token(jsonObject.getString("access_token")); accessTokenInfo.setRefresh_token(jsonObject.getString("refresh_token")); accessTokenInfo.setExpires_in(jsonObject.getInt("expires_in")); accessTokenInfo.setToken_type(jsonObject.getString("token_type")); return accessTokenInfo; } catch (NoSuchAlgorithmException | KeyManagementException | IOException | JSONException e) { log.error(e.getMessage()); throw new AccessTokenException("Configuration Error for Access Token Generation"); } catch (NullPointerException e) { return null; } }
@Override public long setTargetVersion(PublishingTargetItem target, long newVersion, String site) { long resoponseVersion = -1; if (target.getVersionUrl() != null && !target.getVersionUrl().isEmpty()) { LOGGER.debug("Set deployment agent version for target {0}", target.getName()); URL versionUrl = null; try { versionUrl = new URL(target.getVersionUrl()); } catch (MalformedURLException e) { LOGGER.error("Invalid set version URL for target [%s]", target.getName()); return resoponseVersion; } PostMethod postMethod = null; HttpClient client = null; try { postMethod = new PostMethod(target.getVersionUrl()); postMethod.addParameter(TARGET_REQUEST_PARAMETER, target.getTarget()); postMethod.addParameter(VERSION_REQUEST_PARAMETER, String.valueOf(newVersion)); String siteId = target.getSiteId(); if (StringUtils.isEmpty(siteId)) { siteId = site; } postMethod.addParameter(SITE_REQUEST_PARAMETER, site); client = new HttpClient(); int status = client.executeMethod(postMethod); if (status == HttpStatus.SC_OK) { String responseText = postMethod.getResponseBodyAsString(); if (responseText != null && !responseText.isEmpty()) { resoponseVersion = Long.parseLong(responseText); } else { resoponseVersion = 0; } } } catch (Exception e) { LOGGER.error( "Target {0} responded with error while setting target version. Set version failed for url {1}", target.getName(), target.getVersionUrl()); } finally { if (client != null) { HttpConnectionManager mgr = client.getHttpConnectionManager(); if (mgr instanceof SimpleHttpConnectionManager) { ((SimpleHttpConnectionManager) mgr).shutdown(); } } if (postMethod != null) { postMethod.releaseConnection(); } postMethod = null; client = null; } } return resoponseVersion; }
public static void main(String[] args) { Date now; now = new Date(); System.out.println("Time is :" + now); // Create Repetitively task for every 1 secs HttpClient client = null; PostMethod method = null; JSONObject joResponse = null; try { client = new HttpClient(); // method = new PostMethod("http://23.23.129.228/getLocations.php"); method = new PostMethod("http://54.235.163.80/getLocations.php"); method.addParameter("f", "json"); method.setRequestHeader("Connection", "close"); int statusCode = client.executeMethod(method); System.out.println(statusCode); String responseStream = method.getResponseBodyAsString(); HashSet<String> activeLocations = new HashSet<String>(); if (statusCode == HttpURLConnection.HTTP_OK && responseStream.trim().startsWith("{") && responseStream.trim().endsWith("}")) { StringBuilder keyStrbuildr = new StringBuilder(); joResponse = JSONObject.fromObject(responseStream); // JSONObject locationresp = (JSONObject) joResponse.get("data"); System.out.println(joResponse.getString("data")); System.out.println(!joResponse.getString("data").equals("[]")); /*System.out.println(locationresp); for (Object key: locationresp.keySet()) { String keyStr = (String) key; activeLocations.add(keyStr.split(":")[0]); keyStrbuildr.append("'") .append(keyStr.split(":")[0]) .append("',"); } System.out.println(keyStrbuildr);*/ } else { System.out.println("no response from the wpt server"); } } catch (Exception e) { System.out.println(e); } }
private String sendRequest(TicketsRequest request) throws HttpException, IOException { String html = ""; GetMethod get = new GetMethod(url2); client.executeMethod(get); int statusCodeInit = client.executeMethod(get); if (statusCodeInit != HttpStatus.SC_OK) { logger.error("sendRequest method failed. Get method failed: " + get.getStatusLine()); return null; } else { html = IOUtils.toString(get.getResponseBodyAsStream(), "UTF-8"); } parseToken(html); client.getHttpConnectionManager().getParams().setSoTimeout(10000); PostMethod post = new PostMethod(URL); post.addRequestHeader("Accept", "*/*"); post.addRequestHeader("Accept-Encoding", "gzip, deflate"); post.addRequestHeader("Accept-Language", "uk,ru;q=0.8,en-US;q=0.5,en;q=0.3"); // post.addRequestHeader("Cache-Control", "no-cache"); post.addRequestHeader("Connection", "keep-alive"); // post.addRequestHeader("Content-Length", "288"); //202. 196 post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); post.addRequestHeader("GV-Ajax", "1"); post.addRequestHeader("GV-Referer", "http://booking.uz.gov.ua/"); post.addRequestHeader("GV-Screen", "1920x1080"); post.addRequestHeader("GV-Token", token); post.addRequestHeader("GV-Unique-Host", "1"); post.addRequestHeader("Host", "booking.uz.gov.ua"); // post.addRequestHeader("Pragma", "no-cache"); post.addRequestHeader("Origin", "http://booking.uz.gov.ua"); post.addRequestHeader("Referer", "http://booking.uz.gov.ua/"); post.addRequestHeader( "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/39.0"); post.addParameter("another_ec", "0"); post.addParameter("date_dep", new SimpleDateFormat("dd.MM.yyyy").format(request.date)); post.addParameter("search", ""); post.addParameter("station_from", request.from.getName()); post.addParameter("station_id_from", request.from.getStationId()); post.addParameter("station_id_till", request.till.getStationId()); post.addParameter("station_till", request.till.getName()); post.addParameter("time_dep", "00:00"); post.addParameter("time_dep_till", ""); int statusCode = client.executeMethod(post); if (statusCode != HttpStatus.SC_OK) { logger.error("sendRequest method failed. Post method failed: " + post.getStatusLine()); return null; } return post.getResponseBodyAsString(); }
/** * Parse successful JSON response * * @param method * @param currentTime * @return */ private void parseResponse(PostMethod method, Long currentTime) { int statusCode = method.getStatusCode(); String accessToken = ""; if (statusCode == 200) { JSONObject rpcObject; try { rpcObject = new JSONObject(method.getResponseBodyAsString()); accessToken = rpcObject.getString("access_token"); String refreshToken = rpcObject.getString("refresh_token"); String expires_in = rpcObject.getString("expires_in"); Long accessTokenExpiry = null; if (expires_in.equals("0")) { accessTokenExpiry = currentTime + ACCESSTOKEN_EXPIRY; // 100 // years } Long refreshTokenExpiry = currentTime + REFRESHTOKEN_EXPIRY; oauthResponse.setStatus(true); oauthResponse.setAccessToken(accessToken); oauthResponse.setRefreshToken(refreshToken); oauthResponse.setAccessTokenExpiry(accessTokenExpiry); oauthResponse.setRefreshTokenExpiry(refreshTokenExpiry); } catch (ParseException e) { setErrorResponse(statusCode, e.getMessage()); } catch (IOException e) { setErrorResponse(statusCode, e.getMessage()); } } else { try { String errorResponse = method.getResponseBodyAsString() == null ? method.getStatusText() : method.getResponseBodyAsString(); setErrorResponse(statusCode, errorResponse); } catch (IOException e) { setErrorResponse(statusCode, e.getMessage()); } } }
@Test public void findCoverProject() throws Exception { HttpClient httpClient = new HttpClient(); // String url = "http://localhost:8080/rental/rent/entry.html"; String url = "http://localhost:8080/rental/pay/unify"; PostMethod postMethod = new PostMethod(url); String charSet = "UTF-8"; httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charSet); String a = "<xml><a>1</a><return_code>SUCCESS</return_code><return_msg></return_msg><appid>wx8276ac869116d5aa</appid><mch_id>10058488</mch_id><nonce_str></nonce_str><sign></sign><result_code>SUCCESS</result_code><err_code></err_code><err_code_des></err_code_des><openid>o00MJjxDIObA_dpqLSnnewODPVx8</openid><is_subscribe>N</is_subscribe><trade_type>JSAPI</trade_type><bank_type>bankType</bank_type><total_fee>1000</total_fee><coupon_fee></coupon_fee><fee_type></fee_type><transaction_id>12345678901234567890123456789012</transaction_id><out_trade_no>test7764262942</out_trade_no><time_end>20141231100001</time_end></xml>"; postMethod.setRequestBody(a); int statusCode = httpClient.executeMethod(postMethod); System.out.println(postMethod.getResponseBodyAsString()); }