public static byte[] post(String url, RequestEntity requestEntity) throws Exception { PostMethod method = new PostMethod(url); method.addRequestHeader("Connection", "Keep-Alive"); method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); method .getParams() .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); method.setRequestEntity(requestEntity); method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); try { int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("httpCode=" + statusCode); return method.getResponseBody(); } return method.getResponseBody(); } catch (SocketTimeoutException e) { e.printStackTrace(); return null; } catch (Exception e) { e.printStackTrace(); return null; } finally { method.releaseConnection(); } }
private PostMethod convertHttpServletRequestToPostMethod(String url, HttpServletRequest request) { PostMethod postMethod = new PostMethod(url); for (Enumeration headers = request.getHeaderNames(); headers.hasMoreElements(); ) { String headerName = (String) headers.nextElement(); String headerValue = (String) request.getHeader(headerName); postMethod.addRequestHeader(headerName, headerValue); } postMethod.removeRequestHeader("Host"); postMethod.addRequestHeader("Host", request.getRequestURL().toString()); for (Enumeration names = request.getParameterNames(); names.hasMoreElements(); ) { String paramName = (String) names.nextElement(); String paramValue = (String) request.getParameter(paramName); postMethod.addParameter(paramName, paramValue); } StringBuilder requestBody = new StringBuilder(); try { BufferedReader reader = request.getReader(); String line; while (null != (line = reader.readLine())) { requestBody.append(line); } reader.close(); } catch (IOException e) { requestBody.append(""); } postMethod.setRequestEntity(new StringRequestEntity(requestBody.toString())); return postMethod; }
/* */ public static byte[] post(String url, RequestEntity requestEntity) /* */ throws Exception /* */ { /* 96 */ PostMethod method = new PostMethod(url); /* 97 */ method.addRequestHeader("Connection", "Keep-Alive"); /* 98 */ method.getParams().setCookiePolicy("ignoreCookies"); /* 99 */ method .getParams() .setParameter("http.method.retry-handler", new DefaultHttpMethodRetryHandler(0, false)); /* 100 */ method.setRequestEntity(requestEntity); /* 101 */ method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); /* */ try /* */ { /* 104 */ int statusCode = client.executeMethod(method); /* 105 */ if (statusCode != 200) { /* 106 */ return null; /* */ } /* 108 */ return method.getResponseBody(); /* */ } /* */ catch (SocketTimeoutException e) { /* 111 */ return null; /* */ } catch (Exception e) { /* 113 */ return null; /* */ } finally { /* 115 */ method.releaseConnection(); /* */ } /* */ }
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; } }
public void resetMethod() { // httpClient.getState().clearCookies(); httpClient = clientMap.get(account.getUsername()); // for(String s1:account.getCookie().split("; ")){ // Cookie cookie = new Cookie(domain, name, value) // httpClient.getState().addCookie(cookie); // } httpMethod = new GetMethod(); // for (Header h : httpMethod.getRequestHeaders()) { // httpMethod.removeRequestHeader(h); // } // httpClient.getState().clearCookies(); httpMethod.addRequestHeader( "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36"); httpMethod.addRequestHeader("Host", "weibo.com"); httpMethod.addRequestHeader("Connection", "keep-alive"); httpMethod.addRequestHeader("Accept-Language", "zh-CN,zh;q=0.8"); httpMethod.addRequestHeader("Cache-Control", "max-age=0"); httpMethod.addRequestHeader( "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); httpMethod.addRequestHeader("Accept-Encoding", "deflate,sdch"); httpMethod.removeRequestHeader("Cookie"); // ck = // "__utma=15428400.1695645915.1351319378.1351319378.1351319378.1; // SINAGLOBAL=1743311276659.3694.1359040897731; ssoln=18260402168%40139.com; myuid=2350795254; // [email protected]; wvr=5; UOR=www.juyouqu.com,widget.weibo.com,login.sina.com.cn; // UV5PAGE=usr513_160; // SUE=es%3D6edfb5cebc465646c2b99373cb2a29fe%26ev%3Dv1%26es2%3D2d0e68c7608a20158aa2045b5dfb59ee%26rs0%3DcEHTC0Ck28iBwSm7ReH2rIUG1n%252FJjjyJ3TkFC8oU2gEFF7qEa83xCOp%252FdFSR05fBeMEZuKAm5ZMBr721u67n7Rfq7KrNI7cHkJFqnvrl1ut%252Bid0pcoUAmyM9JP316GEN%252FB9E1AqHJns7jVNcflxekc2QPaMOf4BzOUX7zShB0LM%253D%26rv%3D0; SUP=cv%3D1%26bt%3D1383912034%26et%3D1383998434%26d%3Dc909%26i%3D15d3%26us%3D1%26vf%3D0%26vt%3D0%26ac%3D2%26st%3D0%26uid%3D3807150373%26name%3Djobpassion%2540gmail.com%26nick%3D%25E6%25B5%25B7%25E6%25B7%2598%25E8%25B5%2584%25E8%25AE%25AF2013%26fmp%3D%26lcp%3D2013-10-08%252021%253A20%253A24; SUS=SID-3807150373-1383912034-JA-jqf3k-628deb26b5773de29473c3d67d64b10b; ALF=1386504033; SSOLoginState=1383912034; UUG=usrmdins41458; _s_tentry=weibo.com; Apache=8601501327939.331.1383912035126; ULV=1383912035149:97:5:3:8601501327939.331.1383912035126:1383837545412; UV5=usrmdins311164; SinaRot_wb_r_topic=75" // httpMethod.addRequestHeader("Cookie", account.getCookie()); // postMethod.recycle(); postMethod = new PostMethod(); postMethod.addRequestHeader( "User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36"); postMethod.addRequestHeader("Host", "weibo.com"); postMethod.addRequestHeader("Connection", "keep-alive"); postMethod.addRequestHeader("Accept-Language", "zh-CN,zh;q=0.8"); // postMethod.addRequestHeader("Cache-Control", "max-age=0"); postMethod.addRequestHeader("Accept", "*/*"); postMethod.addRequestHeader("Accept-Encoding", "deflate,sdch"); postMethod.addRequestHeader("Origin", "http://weibo.com"); // postMethod.addRequestHeader("Content-Length", "101"); postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); postMethod.addRequestHeader("X-Requested-With", "XMLHttpRequest"); postMethod.addRequestHeader("Referer", "http://weibo.com/xiena?refer=interest"); // postMethod.addRequestHeader("Cookie", account.getCookie()); }
private static JSONObject generateSignature(String pageId) throws Exception { HttpClient httpClient = new HttpClient(); PostMethod postRequest = new PostMethod(endPoint); postRequest.addRequestHeader("apiAccessKeyId", username); postRequest.addRequestHeader("apiSecretAccessKey", password); postRequest.addRequestHeader("Accept", "application/json"); RequestEntity requestEntity = new StringRequestEntity(buildJsonRequest(pageId), "application/json", "UTF-8"); postRequest.setRequestEntity(requestEntity); // Re-try 10 times in case the server is too busy to give you response in time. int loop = 0; while (loop++ < 10) { int response = httpClient.executeMethod(postRequest); if (response == 404) { throw new Exception( "Failed with HTTP error code : " + response + ". ZUORA Signature API End Point is incorrect."); } else if (response == 401) { throw new Exception( "Failed with HTTP error code : " + response + ". ZUORA Login's Username or Password is incorrect."); } else if (response != 200) { throw new Exception( "Failed with HTTP error code : " + response + ". ZUORA Login's Username or Password is incorrect."); } if (postRequest.getResponseBody().length > 0) { break; } } // Parse the response returned from ZUORA Signature API End Point byte[] res = postRequest.getResponseBody(); String s = new String(res); JSONObject result = new JSONObject(s); if (!result.getBoolean("success")) { throw new Exception( "Failed to generate signature. The reason is " + result.getString("reasons")); } return result; }
public String jasperAuthen(String username, String password) throws HttpException, IOException { logger.info("Authenticate : Jasper Report Server"); Header[] headers = null; String sessionCookie = ""; this.httpClient = new HttpClient(); PostMethod mPost = new PostMethod(restLoginUrl); Header mtHeader = new Header(); mtHeader.setName("content-type"); mtHeader.setValue("application/x-www-form-urlencoded"); mtHeader.setName("accept"); mPost.addParameter("j_username", username); mPost.addParameter("j_password", password); mPost.addRequestHeader(mtHeader); httpClient.executeMethod(mPost); headers = mPost.getResponseHeaders(); mPost.releaseConnection(); sessionCookie = headers[2].getValue(); logger.debug("SessionCookie is {}", sessionCookie); return sessionCookie; }
private static String[] httpPost(String url, String xml) throws Exception { HttpClient client = new HttpClient(); HttpState state = client.getState(); Credentials credentials = new UsernamePasswordCredentials("S2VMS", "S2VMS!Q@W#E"); state.setCredentials(null, null, credentials); client.setState(state); PostMethod method = new PostMethod(url); method.setDoAuthentication(true); method.getHostAuthState().setAuthAttempted(true); method.getHostAuthState().setAuthRequested(true); method.getHostAuthState().setPreemptive(); method.addRequestHeader("Content-Type", "text/xml"); method.addRequestHeader("SOAPAction", "http://tempuri.org/GetLinkMedia"); try { method.setRequestBody(xml); } catch (Exception e) { try { ByteArrayRequestEntity entity = new ByteArrayRequestEntity(xml.getBytes()); method.setRequestEntity(entity); } catch (Exception e1) { throw new Exception("Impossible to set the xml in the post"); } } int iRes = client.executeMethod(method); byte[] response = method.getResponseBody(); String textResponse = new String(response); String[] toReturn = {"" + iRes, textResponse}; return toReturn; }
protected static PostMethod httpPost(String path, String body) throws IOException { LOG.info("Connecting to {}", url + path); HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url + path); postMethod.addRequestHeader("Origin", url); RequestEntity entity = new ByteArrayRequestEntity(body.getBytes("UTF-8")); postMethod.setRequestEntity(entity); httpClient.executeMethod(postMethod); LOG.info("{} - {}", postMethod.getStatusCode(), postMethod.getStatusText()); return postMethod; }
public void produceMessages() throws Exception { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(MessagingServiceMessagesURL); Base64 base64 = new Base64(); String base64Credentials = new String(base64.encode("admin:admin".getBytes())); method.addRequestHeader(new Header("Authorization", "Basic " + base64Credentials)); method.setRequestEntity(new StringRequestEntity("Hello !", "text/plain", "UTF-8")); int status = client.executeMethod(method); if (HttpResponseCodes.SC_OK != status) { throw new RuntimeException("Messages can not be sent"); } }
public void registerMessagingServiceScopes(String consumerKey, String scope) throws Exception { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(ConsumerScopesRegistrationURL); Base64 base64 = new Base64(); String base64Credentials = new String(base64.encode("admin:admin".getBytes())); method.addRequestHeader(new Header("Authorization", "Basic " + base64Credentials)); method.addParameter(OAuth.OAUTH_CONSUMER_KEY, consumerKey); method.addParameter("xoauth_scope", scope); method.addParameter("xoauth_permission", "sendMessages"); int status = client.executeMethod(method); if (HttpResponseCodes.SC_OK != status) { throw new RuntimeException("Scopes can not be registered"); } }
/** * Sends a synchronous message, waits for the result, and returns the result. This method blocks * until either a result has been retrieved, a send error has occurred, or the thread was * interrupted. * * @param message the message to be sent * @return the resulting incoming message * @throws SynchronousSendException * @throws InterruptedException */ public IncomingMessage sendMessageSynchronous(OutgoingMessage message) throws SynchronousSendException, InterruptedException { PostMethod method = new PostMethod(message.getTargetURL()); // Set parameters: // -> Do not retry // -> Socket timeout to default timeout value. method .getParams() .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(1, false)); method .getParams() .setParameter(HttpMethodParams.SO_TIMEOUT, new Integer(BPELUnitRunner.getTimeout())); method.addRequestHeader("SOAPAction", "\"" + message.getSOAPHTTPAction() + "\""); RequestEntity entity; try { entity = new StringRequestEntity( message.getBody(), BPELUnitConstants.TEXT_XML_CONTENT_TYPE, BPELUnitConstants.DEFAULT_HTTP_CHARSET); } catch (UnsupportedEncodingException e) { // cannot happen since we use the default HTTP Encoding. throw new SynchronousSendException( "Unsupported encoding when trying to post message to web service.", e); } method.setRequestEntity(entity); try { // Execute the method. int statusCode = fClient.executeMethod(method); String responseBody = method.getResponseBodyAsString(); IncomingMessage returnMsg = new IncomingMessage(); returnMsg.setStatusCode(statusCode); returnMsg.setBody(responseBody); return returnMsg; } catch (Exception e) { if (isAborting()) { throw new InterruptedException(); } else throw new SynchronousSendException(e); } finally { // Release the connection. method.releaseConnection(); } }
public HttpRequest(Method method, String url, Object payload) throws Exception { if (method == Method.POST) { PostMethod post = new PostMethod(url); post.addRequestHeader("Accept", "application/json"); String content = new BeanToJsonConverter().convert(payload); post.setRequestEntity(new StringRequestEntity(content, "application/json", "UTF-8")); new HttpClient().executeMethod(post); return; } throw new RuntimeException("Unsupported method"); }
// TODO : the subscriber may need to provide some form of id known // to the message receiver so that the receiver can validate that it was indeed // the subscriber who asked the service to push the messages; // however, the consumerId creates by the subscriber can be enough; // Question : what about refresh tokens ? public void registerMessagingServiceCallback( String consumerKey, String consumerSecret, String callback) throws Exception { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(MessagingServiceCallbackRegistrationURL); Base64 base64 = new Base64(); String base64Credentials = new String(base64.encode("admin:admin".getBytes())); method.addRequestHeader(new Header("Authorization", "Basic " + base64Credentials)); method.addParameter("consumer_id", consumerKey); method.addParameter("consumer_secret", consumerSecret); method.addParameter("callback_uri", callback); int status = client.executeMethod(method); if (HttpResponseCodes.SC_OK != status) { throw new RuntimeException("Callback Registration failed"); } }
public static String HttpPostForLogistics(String url, String method, String str) { String encoding = "UTF-8"; String webUrl = url + "/" + method; StringBuffer sBuffer = new StringBuffer(); // 构造HttpClient的实例 HttpClient httpClient = new HttpClient(); // 创建POS方法的实例 PostMethod postMethod = new PostMethod(webUrl); try { // postMethod.setRequestEntity(new ByteArrayRequestEntity(str.getBytes(),"application/json; // charset=utf-8")); postMethod.setRequestBody(str); } catch (Exception e1) { e1.printStackTrace(); } postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000); // 连接5秒超时 httpClient.getHttpConnectionManager().getParams().setSoTimeout(30000); // 读取30秒超时 // postMethod.setRequestHeader("Content-type", "application/json; charset=utf-8"); // postMethod.setDoAuthentication(false); // postMethod.addRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT // 5.1)"); postMethod.setDoAuthentication(true); postMethod.addRequestHeader("Authorization", "Basic U0FQX0FNOkFubmllTWFvMTIzNA=="); postMethod.setRequestHeader("Content-type", "application/json"); try { // 执行getMethod int statusCode = httpClient.executeMethod(postMethod); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + postMethod.getStatusLine()); sBuffer = new StringBuffer(); } else { sBuffer = new StringBuffer(postMethod.getResponseBodyAsString() + ""); } } catch (HttpException e) { // 发生致命的异常,可能是协议不对或者返回的内容有问题 System.out.println("Please check your provided http address!"); e.printStackTrace(); } catch (IOException e) { // 发生网络异常 e.printStackTrace(); } finally { // 释放连接 postMethod.releaseConnection(); } return sBuffer.toString(); }
/** * Invoke API end point to get the new set of tokens * * @param clientIdAut * @param clientSecretAut * @param requestBody * @return */ private PostMethod sendReceive(String clientIdAut, String clientSecretAut, String requestBody) { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(this.endPoint); method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); method.setRequestEntity(new StringRequestEntity(requestBody)); try { client.executeMethod(method); return method; } catch (HttpException e) { setErrorResponse(method.getStatusCode(), e.getMessage()); } catch (IOException e) { setErrorResponse(method.getStatusCode(), e.getMessage()); } return method; }
/** * Sends a new HTTP request to a server through a proxy. * * @param requestParameters a set of parameters that will set the content of the request and * specify the proxy it should go through */ public void callWilmaTestServer( final RequestParameters requestParameters, final TestClientParameters clientParameters) { try { HttpClient httpClient = new HttpClient(); PostMethod httpPost = new PostMethod(requestParameters.getTestServerUrl()); if (clientParameters.isUseProxy()) { httpClient .getHostConfiguration() .setProxy(requestParameters.getWilmaHost(), requestParameters.getWilmaPort()); } InputStream inputStream = requestParameters.getInputStream(); if (requestParameters.getContentType().contains("fastinfoset")) { inputStream = compress(inputStream); } if (requestParameters.getContentEncoding().contains("gzip")) { inputStream = encode(inputStream); httpPost.setRequestHeader("Content-Encoding", requestParameters.getContentEncoding()); } InputStreamRequestEntity entity = new InputStreamRequestEntity(inputStream, requestParameters.getContentType()); httpPost.setRequestEntity(entity); httpPost.setRequestHeader("Accept", requestParameters.getAcceptHeader()); httpPost.addRequestHeader("Accept-Encoding", requestParameters.getAcceptEncoding()); // httpPost.addRequestHeader("0", "WilmaBypass=true"); httpClient .getHttpConnectionManager() .getParams() .setSendBufferSize(clientParameters.getRequestBufferSize()); httpClient .getHttpConnectionManager() .getParams() .setReceiveBufferSize(clientParameters.getResponseBufferSize()); int statusCode = httpClient.executeMethod(httpPost); logger.info("status code: " + statusCode); if (clientParameters.getAllowResponseLogging()) { logger.info(getInputStreamAsString(httpPost.getResponseBodyAsStream())); } } catch (UnsupportedEncodingException e) { throw new SystemException("Unsupported encoding.", e); } catch (HttpException e) { throw new SystemException("Http exception occurred.", e); } catch (IOException e) { throw new SystemException("InputStream cannot be read.", e); } }
private void doAuthentication(URL jenkinsUrl) throws AuthenticationException { if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) { httpClient .getState() .setCredentials( new AuthScope(jenkinsUrl.getHost(), jenkinsUrl.getPort()), new UsernamePasswordCredentials(username, password)); } httpClient.getParams().setAuthenticationPreemptive(true); PostMethod post = new PostMethod(jenkinsUrl.toString()); try { if (isCrumbDataSet()) { post.addRequestHeader(CRUMB_NAME, crumbData); } post.setDoAuthentication(true); int responseCode = httpClient.executeMethod(post); final String responseBody; try (InputStream inputStream = post.getResponseBodyAsStream(); ) { responseBody = IOUtils.toString(inputStream, post.getResponseCharSet()); } if (responseCode != HttpURLConnection.HTTP_OK) { checkResponse(responseCode, responseBody); } } catch (HttpException httpEx) { throw new ConfigurationException( String.format( "HTTP Error during method execution '%s': %s", jenkinsUrl.toString(), httpEx.getMessage()), httpEx); } catch (IOException ioEx) { throw new ConfigurationException( String.format( "IO Error during method execution '%s': %s", jenkinsUrl.toString(), ioEx.getMessage()), ioEx); } finally { post.releaseConnection(); } }
public String registerMessagingService(String consumerKey) throws Exception { HttpClient client = new HttpClient(); PostMethod method = new PostMethod(ConsumerRegistrationURL); Base64 base64 = new Base64(); String base64Credentials = new String(base64.encode("admin:admin".getBytes())); method.addRequestHeader(new Header("Authorization", "Basic " + base64Credentials)); method.addParameter(OAuth.OAUTH_CONSUMER_KEY, consumerKey); int status = client.executeMethod(method); if (HttpResponseCodes.SC_OK != status) { throw new RuntimeException("Registration failed"); } // check that we got all tokens Map<String, String> response = OAuth.newMap(OAuth.decodeForm(method.getResponseBodyAsString())); String secret = response.get("xoauth_consumer_secret"); if (secret == null) { throw new RuntimeException("No secret available"); } return secret; }
@Test public void docDelete() throws UnsupportedEncodingException { String api_url = ""; // httpClient HttpClient httpClient = new HttpClient(); httpClient.getParams().setSoTimeout(6000); httpClient.getParams().setVersion(HttpVersion.HTTP_1_0); httpClient.getParams().setCredentialCharset("UTF-8"); httpClient.getParams().setContentCharset("UTF-8"); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(6000); PostMethod postMethod = new PostMethod(api_url); postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded"); postMethod.addParameter("from", "docquality"); // API 호출하는 운영툴 명칭 postMethod.addParameter("admin_id", "ju0805"); // 삭제요청을 한 운영자 id postMethod.addParameter("query", "콜걸"); // 검색쿼리 postMethod.addParameter("srs", "off"); // 원문삭제여부 postMethod.addParameter("service", "blog"); // 서비스명 postMethod.addParameter("description", "불법"); // 부가코멘트 postMethod.addParameter("action_code", "10401"); // 액션코드 postMethod.addParameter("type", "article"); // 타입 postMethod.addParameter("reason1", "ILLEGAL"); postMethod.addParameter("docurl", "http://blog.daum.net/jjipeter/4"); postMethod.addParameter("docid", "1799508185"); postMethod.addParameter("dsid", "22YGTLTRZlm6NVoLDs"); try { int resCode = httpClient.executeMethod(postMethod); if (resCode == HttpStatus.SC_OK) { JSONObject jsonObejct = new JSONObject(); String contents = postMethod.getResponseBodyAsString(); jsonObejct = JSONObject.fromObject(contents); System.out.println(jsonObejct); } } catch (Exception e) { e.printStackTrace(); } finally { postMethod.releaseConnection(); } }
@Override public void sendMessage(String id, String total, String phone) { // 创建浏览器对象 HttpClient client = new HttpClient(); // 创建post请求 PostMethod post = new PostMethod("http://utf8.sms.webchinese.cn"); post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); post.setParameter("Uid", "gz_shop_ms"); post.setParameter("Key", "0d0dd0eeca547bcb896d"); post.setParameter("smsMob", phone); post.setParameter("smsText", "订单编号为:" + id + ",金额 为: " + total + ",已经支付成功!"); // 发送post请求 try { int code = client.executeMethod(post); System.out.println("http状态码:200代表OK: " + code); // 查看发送结果 System.out.println(post.getResponseBodyAsString()); } catch (Exception e) { throw new RuntimeException(e); } }
/** * Create a node under given path, using a POST to Sling * * @param url under which node is created * @param multiPart if true, does a multipart POST * @return the URL that Sling provides to display the node */ public String createNode( String url, Map<String, String> clientNodeProperties, Map<String, String> requestHeaders, boolean multiPart) throws IOException { final PostMethod post = new PostMethod(url); post.setFollowRedirects(false); // create a private copy of the properties to not tamper with // the properties of the client Map<String, String> nodeProperties = new HashMap<String, String>(); // add sling specific properties nodeProperties.put(":redirect", "*"); nodeProperties.put(":displayExtension", ""); nodeProperties.put(":status", "browser"); // take over any client provided properties if (clientNodeProperties != null) { nodeProperties.putAll(clientNodeProperties); } else { // add fake property - otherwise the node is not created nodeProperties.put("jcr:created", ""); } // force form encoding to UTF-8, which is what we use to convert the // string parts into stream data nodeProperties.put("_charset_", "UTF-8"); if (nodeProperties.size() > 0) { if (multiPart) { final List<Part> partList = new ArrayList<Part>(); for (Map.Entry<String, String> e : nodeProperties.entrySet()) { if (e.getValue() != null) { partList.add(new StringPart(e.getKey().toString(), e.getValue().toString(), "UTF-8")); } } final Part[] parts = partList.toArray(new Part[partList.size()]); post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); } else { for (Map.Entry<String, String> e : nodeProperties.entrySet()) { post.addParameter(e.getKey(), e.getValue()); } } } if (requestHeaders != null) { for (Map.Entry<String, String> e : requestHeaders.entrySet()) { post.addRequestHeader(e.getKey(), e.getValue()); } } final int status = httpClient.executeMethod(post); if (status != 302) { throw new HttpStatusCodeException(302, status, "POST", url); } String location = post.getResponseHeader("Location").getValue(); post.releaseConnection(); // simple check if host is missing if (!location.startsWith("http://")) { String host = HttpTestBase.HTTP_BASE_URL; int idx = host.indexOf('/', 8); if (idx > 0) { host = host.substring(0, idx); } location = host + location; } return location; }
protected void createSwarmSlave(Candidate target) throws IOException, InterruptedException, RetryException { HttpClient client = createHttpClient(new URL(target.url)); // Jenkins does not do any authentication negotiation, // ie. it does not return a 401 (Unauthorized) // but immediately a 403 (Forbidden) String labelStr = StringUtils.join(options.labels, ' '); StringBuilder toolLocationBuilder = new StringBuilder(); if (options.toolLocations != null) { for (Entry<String, String> toolLocation : options.toolLocations.entrySet()) { toolLocationBuilder.append( param("toolLocation", toolLocation.getKey() + ":" + toolLocation.getValue())); } } PostMethod post = new PostMethod( target.url + "/plugin/swarm/createSlave?name=" + options.name + "&executors=" + options.executors + param("remoteFsRoot", options.remoteFsRoot.getAbsolutePath()) + param("description", options.description) + param("labels", labelStr) + toolLocationBuilder.toString() + "&secret=" + target.secret + param("mode", options.mode.toUpperCase(Locale.ENGLISH)) + param("hash", hash)); post.setDoAuthentication(true); post.addRequestHeader("Connection", "close"); Crumb csrfCrumb = getCsrfCrumb(client, target); if (csrfCrumb != null) { post.addRequestHeader(csrfCrumb.crumbRequestField, csrfCrumb.crumb); } int responseCode = client.executeMethod(post); if (responseCode != 200) { throw new RetryException( String.format( "Failed to create a slave on Jenkins CODE: %s%n%s", responseCode, post.getResponseBodyAsString())); } Properties props = new Properties(); InputStream stream = post.getResponseBodyAsStream(); if (stream != null) { try { props.load(stream); } finally { stream.close(); } } String name = props.getProperty("name"); if (name == null) { this.name = options.name; return; } name = name.trim(); if (name.isEmpty()) { this.name = options.name; return; } this.name = name; }
/** * Post a file to the server. The different elements of the post are encoded in the specified * message. * * @param message The message that contains the post information. * @throws SWORDClientException if there is an error during the post operation. */ public DepositResponse postFile(PostMessage message) throws SWORDClientException { if (message == null) { throw new SWORDClientException("Message cannot be null."); } PostMethod httppost = new PostMethod(message.getDestination()); if (doAuthentication) { setBasicCredentials(username, password); httppost.setDoAuthentication(true); } DepositResponse response = null; String messageBody = ""; try { if (message.isUseMD5()) { String md5 = ChecksumUtils.generateMD5(message.getFilepath()); if (message.getChecksumError()) { md5 = "1234567890"; } log.debug("checksum error is: " + md5); if (md5 != null) { httppost.addRequestHeader(new Header(HttpHeaders.CONTENT_MD5, md5)); } } String filename = message.getFilename(); if (!"".equals(filename)) { httppost.addRequestHeader( new Header(HttpHeaders.CONTENT_DISPOSITION, " filename=" + filename)); } if (containsValue(message.getSlug())) { httppost.addRequestHeader(new Header(HttpHeaders.SLUG, message.getSlug())); } if (message.getCorruptRequest()) { // insert a header with an invalid boolean value httppost.addRequestHeader(new Header(HttpHeaders.X_NO_OP, "Wibble")); } else { httppost.addRequestHeader( new Header(HttpHeaders.X_NO_OP, Boolean.toString(message.isNoOp()))); } httppost.addRequestHeader( new Header(HttpHeaders.X_VERBOSE, Boolean.toString(message.isVerbose()))); String packaging = message.getPackaging(); if (packaging != null && packaging.length() > 0) { httppost.addRequestHeader(new Header(HttpHeaders.X_PACKAGING, packaging)); } String onBehalfOf = message.getOnBehalfOf(); if (containsValue(onBehalfOf)) { httppost.addRequestHeader(new Header(HttpHeaders.X_ON_BEHALF_OF, onBehalfOf)); } String userAgent = message.getUserAgent(); if (containsValue(userAgent)) { httppost.addRequestHeader(new Header(HttpHeaders.USER_AGENT, userAgent)); } FileRequestEntity requestEntity = new FileRequestEntity(new File(message.getFilepath()), message.getFiletype()); httppost.setRequestEntity(requestEntity); client.executeMethod(httppost); status = new Status(httppost.getStatusCode(), httppost.getStatusText()); log.info("Checking the status code: " + status.getCode()); if (status.getCode() == HttpStatus.SC_ACCEPTED || status.getCode() == HttpStatus.SC_CREATED) { messageBody = readResponse(httppost.getResponseBodyAsStream()); response = new DepositResponse(status.getCode()); response.setLocation(httppost.getResponseHeader("Location").getValue()); // added call for the status code. lastUnmarshallInfo = response.unmarshall(messageBody, new Properties()); } else { messageBody = readResponse(httppost.getResponseBodyAsStream()); response = new DepositResponse(status.getCode()); response.unmarshallErrorDocument(messageBody); } return response; } catch (NoSuchAlgorithmException nex) { throw new SWORDClientException("Unable to use MD5. " + nex.getMessage(), nex); } catch (HttpException ex) { throw new SWORDClientException(ex.getMessage(), ex); } catch (IOException ioex) { throw new SWORDClientException(ioex.getMessage(), ioex); } catch (UnmarshallException uex) { throw new SWORDClientException(uex.getMessage() + "(<pre>" + messageBody + "</pre>)", uex); } finally { httppost.releaseConnection(); } }
public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception { // digest the message MessageDigest messageDigest = MessageDigest.getInstance(this.digestAlgo); byte[] digest = messageDigest.digest(data); // generate the TSP request BigInteger nonce = new BigInteger(128, new SecureRandom()); TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator(); requestGenerator.setCertReq(true); if (null != this.requestPolicy) { requestGenerator.setReqPolicy(this.requestPolicy); } TimeStampRequest request = requestGenerator.generate(this.digestAlgoOid, digest, nonce); byte[] encodedRequest = request.getEncoded(); // create the HTTP client HttpClient httpClient = new HttpClient(); if (null != this.username) { Credentials credentials = new UsernamePasswordCredentials(this.username, this.password); httpClient.getState().setCredentials(AuthScope.ANY, credentials); } if (null != this.proxyHost) { httpClient.getHostConfiguration().setProxy(this.proxyHost, this.proxyPort); } // create the HTTP POST request PostMethod postMethod = new PostMethod(this.tspServiceUrl); RequestEntity requestEntity = new ByteArrayRequestEntity(encodedRequest, "application/timestamp-query"); postMethod.addRequestHeader("User-Agent", this.userAgent); postMethod.setRequestEntity(requestEntity); // invoke TSP service int statusCode = httpClient.executeMethod(postMethod); if (HttpStatus.SC_OK != statusCode) { LOG.error("Error contacting TSP server " + this.tspServiceUrl); throw new Exception("Error contacting TSP server " + this.tspServiceUrl); } // HTTP input validation Header responseContentTypeHeader = postMethod.getResponseHeader("Content-Type"); if (null == responseContentTypeHeader) { throw new RuntimeException("missing Content-Type header"); } String contentType = responseContentTypeHeader.getValue(); if (!contentType.startsWith("application/timestamp-reply")) { LOG.debug("response content: " + postMethod.getResponseBodyAsString()); throw new RuntimeException("invalid Content-Type: " + contentType); } if (0 == postMethod.getResponseContentLength()) { throw new RuntimeException("Content-Length is zero"); } // TSP response parsing and validation InputStream inputStream = postMethod.getResponseBodyAsStream(); TimeStampResponse timeStampResponse = new TimeStampResponse(inputStream); timeStampResponse.validate(request); if (0 != timeStampResponse.getStatus()) { LOG.debug("status: " + timeStampResponse.getStatus()); LOG.debug("status string: " + timeStampResponse.getStatusString()); PKIFailureInfo failInfo = timeStampResponse.getFailInfo(); if (null != failInfo) { LOG.debug("fail info int value: " + failInfo.intValue()); if (PKIFailureInfo.unacceptedPolicy == failInfo.intValue()) { LOG.debug("unaccepted policy"); } } throw new RuntimeException( "timestamp response status != 0: " + timeStampResponse.getStatus()); } TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken(); SignerId signerId = timeStampToken.getSID(); BigInteger signerCertSerialNumber = signerId.getSerialNumber(); X500Principal signerCertIssuer = signerId.getIssuer(); LOG.debug("signer cert serial number: " + signerCertSerialNumber); LOG.debug("signer cert issuer: " + signerCertIssuer); // TSP signer certificates retrieval CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection", BouncyCastleProvider.PROVIDER_NAME); Collection<? extends Certificate> certificates = certStore.getCertificates(null); X509Certificate signerCert = null; Map<String, X509Certificate> certificateMap = new HashMap<String, X509Certificate>(); for (Certificate certificate : certificates) { X509Certificate x509Certificate = (X509Certificate) certificate; if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal()) && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) { signerCert = x509Certificate; } String ski = Hex.encodeHexString(getSubjectKeyId(x509Certificate)); certificateMap.put(ski, x509Certificate); LOG.debug( "embedded certificate: " + x509Certificate.getSubjectX500Principal() + "; SKI=" + ski); } // TSP signer cert path building if (null == signerCert) { throw new RuntimeException("TSP response token has no signer certificate"); } List<X509Certificate> tspCertificateChain = new LinkedList<X509Certificate>(); X509Certificate certificate = signerCert; do { LOG.debug("adding to certificate chain: " + certificate.getSubjectX500Principal()); tspCertificateChain.add(certificate); if (certificate.getSubjectX500Principal().equals(certificate.getIssuerX500Principal())) { break; } String aki = Hex.encodeHexString(getAuthorityKeyId(certificate)); certificate = certificateMap.get(aki); } while (null != certificate); // verify TSP signer signature timeStampToken.validate(tspCertificateChain.get(0), BouncyCastleProvider.PROVIDER_NAME); // verify TSP signer certificate this.validator.validate(tspCertificateChain, revocationData); LOG.debug("time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime()); byte[] timestamp = timeStampToken.getEncoded(); return timestamp; }
public void run() { AccountManager am = AccountManager.get(getActivity()); Account account = AccountUtils.getCurrentOwnCloudAccount(getActivity()); OwnCloudVersion ocv = new OwnCloudVersion(am.getUserData(account, AccountAuthenticator.KEY_OC_VERSION)); String url = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + AccountUtils.getWebdavPath(ocv); Log.d("share", "sharing for version " + ocv.toString()); if (ocv.compareTo(new OwnCloudVersion(0x040000)) >= 0) { String APPS_PATH = "/apps/files_sharing/"; String SHARE_PATH = "ajax/share.php"; String SHARED_PATH = "/apps/files_sharing/get.php?token="; final String WEBDAV_SCRIPT = "webdav.php"; final String WEBDAV_FILES_LOCATION = "/files/"; WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient( account, getActivity().getApplicationContext()); HttpConnectionManagerParams params = new HttpConnectionManagerParams(); params.setMaxConnectionsPerHost(wc.getHostConfiguration(), 5); // wc.getParams().setParameter("http.protocol.single-cookie-header", true); // wc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); PostMethod post = new PostMethod( am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + APPS_PATH + SHARE_PATH); post.addRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); post.addRequestHeader( "Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL)); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); Log.d("share", mPath + ""); formparams.add(new BasicNameValuePair("sources", mPath)); formparams.add(new BasicNameValuePair("uid_shared_with", "public")); formparams.add(new BasicNameValuePair("permissions", "0")); post.setRequestEntity( new StringRequestEntity(URLEncodedUtils.format(formparams, HTTP.UTF_8))); int status; try { PropFindMethod find = new PropFindMethod(url + "/"); find.addRequestHeader( "Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL)); Log.d("sharer", "" + url + "/"); for (org.apache.commons.httpclient.Header a : find.getRequestHeaders()) { Log.d("sharer-h", a.getName() + ":" + a.getValue()); } int status2 = wc.executeMethod(find); Log.d("sharer", "propstatus " + status2); GetMethod get = new GetMethod(am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + "/"); get.addRequestHeader( "Referer", am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL)); status2 = wc.executeMethod(get); Log.d("sharer", "getstatus " + status2); Log.d("sharer", "" + get.getResponseBodyAsString()); for (org.apache.commons.httpclient.Header a : get.getResponseHeaders()) { Log.d("sharer", a.getName() + ":" + a.getValue()); } status = wc.executeMethod(post); for (org.apache.commons.httpclient.Header a : post.getRequestHeaders()) { Log.d("sharer-h", a.getName() + ":" + a.getValue()); } for (org.apache.commons.httpclient.Header a : post.getResponseHeaders()) { Log.d("sharer", a.getName() + ":" + a.getValue()); } String resp = post.getResponseBodyAsString(); Log.d("share", "" + post.getURI().toString()); Log.d("share", "returned status " + status); Log.d("share", " " + resp); if (status != HttpStatus.SC_OK || resp == null || resp.equals("") || resp.startsWith("false")) { return; } JSONObject jsonObject = new JSONObject(resp); String jsonStatus = jsonObject.getString("status"); if (!jsonStatus.equals("success")) throw new Exception("Error while sharing file status != success"); String token = jsonObject.getString("data"); String uri = am.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL) + SHARED_PATH + token; Log.d("Actions:shareFile ok", "url: " + uri); } catch (Exception e) { e.printStackTrace(); } } else if (ocv.compareTo(new OwnCloudVersion(0x030000)) >= 0) { } }
public void test() throws Exception { HttpClient client = new HttpClient(); RuntimeStats rt = new RuntimeStats(); rt.songCount.set(15); rt.albumCount.set(5); rt.artistCount.set(2); rt.playlistCount.set(0); rt.userCount.set(2); rt.playtime.set(15); rt.downloaded.set(0); this.addMusicFolder(new File("src/test/resources/data").getAbsolutePath(), rt); rt.songCount.set(24); rt.albumCount.set(6); rt.artistCount.set(3); rt.playtime.set(24); this.addMusicFolder(new File("src/test/resources/data2").getAbsolutePath(), rt); // create playlist with no name: 400 PostMethod post = new PostMethod(URL + "playlist/create"); post.addRequestHeader("sessionId", user_sessionId); client.executeMethod(post); assertEquals(400, post.getStatusCode()); // create playlist 'foo' post = new PostMethod(URL + "playlist/create"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("name", "foo"); client.executeMethod(post); assertEquals(200, post.getStatusCode()); JSONObject obj = new JSONObject(post.getResponseBodyAsString()); Playlist foo = new Playlist(obj.getJSONObject("playlist").toString()); assertEquals("foo", foo.name); assertEquals(0, foo.songs); assertEquals(0, foo.playtime); // create playlist 'foo' again: returns the same playlist post = new PostMethod(URL + "playlist/create"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("name", "foo"); client.executeMethod(post); assertEquals(200, post.getStatusCode()); obj = new JSONObject(post.getResponseBodyAsString()); assertEquals(foo, new Playlist(obj.getJSONObject("playlist").toString())); // create playlist 'foo' as admin: creates another playlist post = new PostMethod(URL + "playlist/create"); post.addRequestHeader("sessionId", admin_sessionId); post.addParameter("name", "foo"); client.executeMethod(post); assertEquals(200, post.getStatusCode()); obj = new JSONObject(post.getResponseBodyAsString()); Playlist pl = new Playlist(obj.getJSONObject("playlist").toString()); assertNotSame(foo, pl); // playlists for user: '******' GetMethod get = new GetMethod(URL + "playlists"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals(1, obj.getJSONArray("playlists").length()); assertEquals(foo, new Playlist(obj.getJSONArray("playlists").get(0).toString())); // playlists/id for user: '******' get = new GetMethod(URL + "playlists/" + user_userId); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals(1, obj.getJSONArray("playlists").length()); assertEquals(foo, new Playlist(obj.getJSONArray("playlists").get(0).toString())); // remove playlist without argument: 400 post = new PostMethod(URL + "playlists/remove"); post.addRequestHeader("sessionId", user_sessionId); client.executeMethod(post); assertEquals(400, post.getStatusCode()); // remove admin 'foo' playlist as user: 403 post = new PostMethod(URL + "playlists/remove"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("playlist_ids[]", "" + pl.id); client.executeMethod(post); assertEquals(403, post.getStatusCode()); // remove admin 'foo' post = new PostMethod(URL + "playlists/remove"); post.addRequestHeader("sessionId", admin_sessionId); post.addParameter("playlist_ids[]", "" + pl.id); client.executeMethod(post); assertEquals(204, post.getStatusCode()); // playlists for admin: 'none' get = new GetMethod(URL + "playlists"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals(0, obj.getJSONArray("playlists").length()); // playlists/id for admin: 'none' get = new GetMethod(URL + "playlists/" + admin_userId); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals(0, obj.getJSONArray("playlists").length()); // playlist/create-add with no name : 400 post = new PostMethod(URL + "playlist/create-add"); post.addRequestHeader("sessionId", user_sessionId); client.executeMethod(post); assertEquals(400, post.getStatusCode()); // playlist/create-add 'bar' with no songs post = new PostMethod(URL + "playlist/create-add"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("name", "bar"); client.executeMethod(post); assertEquals(200, post.getStatusCode()); obj = new JSONObject(post.getResponseBodyAsString()); assertEquals(0, obj.getInt("added")); Playlist bar = new Playlist(obj.getJSONObject("playlist").toString()); assertEquals("bar", bar.name); assertEquals(0, bar.playtime); assertEquals(0, bar.songs); int[] song_ids = new int[4]; int album_id; // search for 'o': 4 songs, 1 album with 1 song get = new GetMethod(URL + "search/o"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); JSONArray songs = obj.getJSONArray("songs"); for (int i = 0; i < 4; i++) { song_ids[i] = songs.getJSONObject(i).getInt("id"); } JSONObject ok = obj.getJSONArray("albums").getJSONObject(0); album_id = ok.getInt("id"); // playlist/create-add 'bar' with songs post = new PostMethod(URL + "playlist/create-add"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("name", "bar"); post.addParameter("song_ids[]", "" + song_ids[0]); post.addParameter("song_ids[]", "" + song_ids[1]); post.addParameter("song_ids[]", "" + song_ids[2]); post.addParameter("song_ids[]", "" + song_ids[3]); post.addParameter("album_ids[]", "" + album_id); client.executeMethod(post); assertEquals(200, post.getStatusCode()); obj = new JSONObject(post.getResponseBodyAsString()); assertEquals(5, obj.getInt("added")); bar = new Playlist(obj.getJSONObject("playlist").toString()); assertEquals("bar", bar.name); assertEquals(5, bar.playtime); assertEquals(5, bar.songs); // check song list in 'bar' get = new GetMethod(URL + "playlist/" + bar.id + "/songs"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals("bar", obj.getString("name")); JSONArray arr = obj.getJSONArray("playlist"); assertEquals(5, arr.length()); for (int i = 0; i < 4; i++) { assertEquals( new Song(songs.getJSONObject(i).toString()), new Song(arr.getJSONObject(i).toString())); } Song s5 = new Song(arr.getJSONObject(4).toString()); assertEquals("Ok", s5.album_name); // playlist/remove song as wrong user post = new PostMethod(URL + "playlist/" + bar.id + "/remove"); post.addRequestHeader("sessionId", admin_sessionId); post.addParameter("song_ids[]", "" + song_ids[0]); client.executeMethod(post); assertEquals(403, post.getStatusCode()); // playlist/remove 2 songs post = new PostMethod(URL + "playlist/" + bar.id + "/remove"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("song_ids[]", "" + song_ids[1]); post.addParameter("song_ids[]", "" + song_ids[2]); client.executeMethod(post); assertEquals(204, post.getStatusCode()); // check song list get = new GetMethod(URL + "playlist/" + bar.id + "/songs"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals("bar", obj.getString("name")); arr = obj.getJSONArray("playlist"); assertEquals(3, arr.length()); assertEquals( new Song(songs.getJSONObject(0).toString()), new Song(arr.getJSONObject(0).toString())); assertEquals( new Song(songs.getJSONObject(3).toString()), new Song(arr.getJSONObject(1).toString())); assertEquals(s5, new Song(arr.getJSONObject(2).toString())); // re-check with song/id/pos get = new GetMethod(URL + "playlist/" + bar.id + "/song/0"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()).getJSONObject("song"); assertEquals(new Song(songs.getJSONObject(0).toString()), new Song(obj.toString())); // 2nd song get = new GetMethod(URL + "playlist/" + bar.id + "/song/1"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()).getJSONObject("song"); assertEquals(new Song(songs.getJSONObject(3).toString()), new Song(obj.toString())); // 3rd song get = new GetMethod(URL + "playlist/" + bar.id + "/song/2"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()).getJSONObject("song"); assertEquals(s5, new Song(obj.toString())); // no more song in playlist get = new GetMethod(URL + "playlist/" + bar.id + "/song/3"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(404, get.getStatusCode()); // playlist/create-add 'bar' with other songs and clear post = new PostMethod(URL + "playlist/create-add"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("name", "bar"); post.addParameter("clear", "true"); post.addParameter("album_ids[]", "" + album_id); client.executeMethod(post); assertEquals(200, post.getStatusCode()); obj = new JSONObject(post.getResponseBodyAsString()); assertEquals(1, obj.getInt("added")); bar = new Playlist(obj.getJSONObject("playlist").toString()); assertEquals("bar", bar.name); assertEquals(1, bar.playtime); assertEquals(1, bar.songs); // playlist/add as admin: 403 post = new PostMethod(URL + "playlist/" + bar.id + "/add"); post.addRequestHeader("sessionId", admin_sessionId); post.addParameter("clear", "true"); post.addParameter("song_ids", "" + s5.id); client.executeMethod(post); assertEquals(403, post.getStatusCode()); // playlist/add with duplicate songs: 400 post = new PostMethod(URL + "playlist/" + bar.id + "/add"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("clear", "true"); post.addParameter("song_ids[]", "" + song_ids[0]); post.addParameter("song_ids[]", "" + song_ids[0]); post.addParameter("album_ids[]", "" + album_id); client.executeMethod(post); assertEquals(500, post.getStatusCode()); // playlist/add a couple songs w/ clear post = new PostMethod(URL + "playlist/" + bar.id + "/add"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("clear", "true"); post.addParameter("song_ids[]", "" + song_ids[0]); post.addParameter("song_ids[]", "" + song_ids[2]); client.executeMethod(post); assertEquals(200, post.getStatusCode()); obj = new JSONObject(post.getResponseBodyAsString()); assertEquals(2, obj.getInt("added")); pl = new Playlist(obj.getJSONObject("playlist").toString()); assertEquals(2, pl.playtime); assertEquals(2, pl.songs); assertEquals("bar", pl.name); // check song list get = new GetMethod(URL + "playlist/" + pl.id + "/songs"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals("bar", obj.getString("name")); arr = obj.getJSONArray("playlist"); assertEquals(2, arr.length()); assertEquals( new Song(songs.getJSONObject(0).toString()), new Song(arr.getJSONObject(0).toString())); assertEquals( new Song(songs.getJSONObject(2).toString()), new Song(arr.getJSONObject(1).toString())); // re-check with song/id/pos get = new GetMethod(URL + "playlist/" + pl.id + "/song/0"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()).getJSONObject("song"); assertEquals(new Song(songs.getJSONObject(0).toString()), new Song(obj.toString())); // 2nd song get = new GetMethod(URL + "playlist/" + pl.id + "/song/1"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()).getJSONObject("song"); assertEquals(new Song(songs.getJSONObject(2).toString()), new Song(obj.toString())); // no more song in playlist get = new GetMethod(URL + "playlist/" + pl.id + "/song/2"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(404, get.getStatusCode()); // random playlist with no name : 400 post = new PostMethod(URL + "playlist/random"); post.addRequestHeader("sessionId", user_sessionId); client.executeMethod(post); assertEquals(400, post.getStatusCode()); // random playlist with no song number : 400 post = new PostMethod(URL + "playlist/random"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("name", "toto"); client.executeMethod(post); assertEquals(400, post.getStatusCode()); // random playlist with too many songs: 400 post = new PostMethod(URL + "playlist/random"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("number", "60"); post.addParameter("name", "toto"); client.executeMethod(post); assertEquals(400, post.getStatusCode()); // random playlist 'toto' post = new PostMethod(URL + "playlist/random"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("number", "15"); post.addParameter("name", "toto"); client.executeMethod(post); assertEquals(200, post.getStatusCode()); obj = new JSONObject(post.getResponseBodyAsString()); assertEquals(15, obj.getInt("added")); Playlist rand = new Playlist(obj.getJSONObject("playlist").toString()); assertEquals(15, rand.playtime); assertEquals(15, rand.songs); assertEquals("toto", rand.name); // get first song get = new GetMethod(URL + "playlist/" + rand.id + "/song/0"); get.addRequestHeader("sessionId", admin_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); Song s = new Song(new JSONObject(get.getResponseBodyAsString()).getJSONObject("song").toString()); assertEquals(s.id, obj.getInt("first_song")); // all random songs should fit in this hashset HashSet<Song> randSet = new HashSet<Song>(15); get = new GetMethod(URL + "playlist/" + rand.id + "/songs"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals("toto", obj.get("name")); arr = obj.getJSONArray("playlist"); assertEquals(15, arr.length()); for (int i = 0; i < arr.length(); i++) { Song ss = new Song(arr.getJSONObject(i).toString()); assertFalse(randSet.contains(ss)); randSet.add(ss); } // there are 24 songs total in library, try to create a 30 songs playlist post = new PostMethod(URL + "playlist/random"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("number", "30"); post.addParameter("name", "titi"); client.executeMethod(post); assertEquals(200, post.getStatusCode()); obj = new JSONObject(post.getResponseBodyAsString()); assertEquals(24, obj.getInt("added")); rand = new Playlist(obj.getJSONObject("playlist").toString()); assertEquals(24, rand.playtime); assertEquals(24, rand.songs); assertEquals("titi", rand.name); // all 24 random songs should fit in this hashset randSet = new HashSet<Song>(24); get = new GetMethod(URL + "playlist/" + rand.id + "/songs"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals("titi", obj.get("name")); arr = obj.getJSONArray("playlist"); assertEquals(24, arr.length()); for (int i = 0; i < arr.length(); i++) { Song ss = new Song(arr.getJSONObject(i).toString()); assertFalse(randSet.contains(ss)); randSet.add(ss); } // re-create 'titi' with 10 songs post = new PostMethod(URL + "playlist/random"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("number", "10"); post.addParameter("name", "titi"); client.executeMethod(post); assertEquals(200, post.getStatusCode()); obj = new JSONObject(post.getResponseBodyAsString()); assertEquals(10, obj.getInt("added")); rand = new Playlist(obj.getJSONObject("playlist").toString()); assertEquals(10, rand.playtime); assertEquals(10, rand.songs); assertEquals("titi", rand.name); // playlists for user: '******', 'bar', 'toto', 'titi' get = new GetMethod(URL + "playlists"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals(4, obj.getJSONArray("playlists").length()); foo = new Playlist(obj.getJSONArray("playlists").get(0).toString()); bar = new Playlist(obj.getJSONArray("playlists").get(1).toString()); Playlist toto = new Playlist(obj.getJSONArray("playlists").get(2).toString()); Playlist titi = new Playlist(obj.getJSONArray("playlists").get(3).toString()); assertEquals("foo", foo.name); assertEquals(0, foo.songs); assertEquals("bar", bar.name); assertEquals(2, bar.songs); assertEquals("toto", toto.name); assertEquals(15, toto.songs); assertEquals("titi", titi.name); assertEquals(10, titi.songs); // remove all 4 user playlists post = new PostMethod(URL + "playlists/remove"); post.addRequestHeader("sessionId", user_sessionId); post.addParameter("playlist_ids[]", "" + foo.id); post.addParameter("playlist_ids[]", "" + bar.id); post.addParameter("playlist_ids[]", "" + toto.id); post.addParameter("playlist_ids[]", "" + titi.id); client.executeMethod(post); assertEquals(204, post.getStatusCode()); // check there are no more user playlists get = new GetMethod(URL + "playlists"); get.addRequestHeader("sessionId", user_sessionId); client.executeMethod(get); assertEquals(200, get.getStatusCode()); obj = new JSONObject(get.getResponseBodyAsString()); assertEquals(0, obj.getJSONArray("playlists").length()); }
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(); }
public NamedList<Object> request(final SolrRequest request, ResponseParser processor) throws SolrServerException, IOException { HttpMethod method = null; InputStream is = null; SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = "/select"; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = _parser; } // The parser 'wt=' and 'version=' params are used instead of the original params ModifiableSolrParams wparams = new ModifiableSolrParams(); wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); if (params == null) { params = wparams; } else { params = new DefaultSolrParams(wparams, params); } if (_invariantParams != null) { params = new DefaultSolrParams(_invariantParams, params); } int tries = _maxRetries + 1; try { while (tries-- > 0) { // Note: since we aren't do intermittent time keeping // ourselves, the potential non-timeout latency could be as // much as tries-times (plus scheduling effects) the given // timeAllowed. try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new GetMethod(_baseURL + path + ClientUtils.toQueryString(params, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = _baseURL + path; boolean isMultipart = (streams != null && streams.size() > 1); if (streams == null || isMultipart) { PostMethod post = new PostMethod(url); post.getParams().setContentCharset("UTF-8"); if (!this.useMultiPartPost && !isMultipart) { post.addRequestHeader( "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<Part> parts = new LinkedList<Part>(); Iterator<String> iter = params.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = params.getParams(p); if (vals != null) { for (String v : vals) { if (this.useMultiPartPost || isMultipart) { parts.add(new StringPart(p, v, "UTF-8")); } else { post.addParameter(p, v); } } } } if (isMultipart) { int i = 0; for (ContentStream content : streams) { final ContentStream c = content; String charSet = null; String transferEncoding = null; parts.add( new PartBase(c.getName(), c.getContentType(), charSet, transferEncoding) { @Override protected long lengthOfData() throws IOException { return c.getSize(); } @Override protected void sendData(OutputStream out) throws IOException { InputStream in = c.getStream(); try { IOUtils.copy(in, out); } finally { in.close(); } } }); } } if (parts.size() > 0) { post.setRequestEntity( new MultipartRequestEntity( parts.toArray(new Part[parts.size()]), post.getParams())); } method = post; } // It is has one stream, it is the post body, put the params in the URL else { String pstr = ClientUtils.toQueryString(params, false); PostMethod post = new PostMethod(url + pstr); // Single stream as body // Using a loop just to get the first one final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { post.setRequestEntity( new RequestEntity() { public long getContentLength() { return -1; } public String getContentType() { return contentStream[0].getContentType(); } public boolean isRepeatable() { return false; } public void writeRequest(OutputStream outputStream) throws IOException { ((RequestWriter.LazyContentStream) contentStream[0]).writeTo(outputStream); } }); } else { is = contentStream[0].getStream(); post.setRequestEntity( new InputStreamRequestEntity(is, contentStream[0].getContentType())); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { // This is generally safe to retry on method.releaseConnection(); method = null; if (is != null) { is.close(); } // If out of tries then just rethrow (as normal error). if ((tries < 1)) { throw r; } // log.warn( "Caught: " + r + ". Retrying..." ); } } } catch (IOException ex) { throw new SolrServerException("error reading streams", ex); } method.setFollowRedirects(_followRedirects); method.addRequestHeader("User-Agent", AGENT); if (_allowCompression) { method.setRequestHeader(new Header("Accept-Encoding", "gzip,deflate")); } try { // Execute the method. // System.out.println( "EXECUTE:"+method.getURI() ); int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { StringBuilder msg = new StringBuilder(); msg.append(method.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append(method.getStatusText()); msg.append("\n\n"); msg.append("request: " + method.getURI()); throw new SolrException(statusCode, java.net.URLDecoder.decode(msg.toString(), "UTF-8")); } // Read the contents String charset = "UTF-8"; if (method instanceof HttpMethodBase) { charset = ((HttpMethodBase) method).getResponseCharSet(); } InputStream respBody = method.getResponseBodyAsStream(); // Jakarta Commons HTTPClient doesn't handle any // compression natively. Handle gzip or deflate // here if applicable. if (_allowCompression) { Header contentEncodingHeader = method.getResponseHeader("Content-Encoding"); if (contentEncodingHeader != null) { String contentEncoding = contentEncodingHeader.getValue(); if (contentEncoding.contains("gzip")) { // log.debug( "wrapping response in GZIPInputStream" ); respBody = new GZIPInputStream(respBody); } else if (contentEncoding.contains("deflate")) { // log.debug( "wrapping response in InflaterInputStream" ); respBody = new InflaterInputStream(respBody); } } else { Header contentTypeHeader = method.getResponseHeader("Content-Type"); if (contentTypeHeader != null) { String contentType = contentTypeHeader.getValue(); if (contentType != null) { if (contentType.startsWith("application/x-gzip-compressed")) { // log.debug( "wrapping response in GZIPInputStream" ); respBody = new GZIPInputStream(respBody); } else if (contentType.startsWith("application/x-deflate")) { // log.debug( "wrapping response in InflaterInputStream" ); respBody = new InflaterInputStream(respBody); } } } } } return processor.processResponse(respBody, charset); } catch (HttpException e) { throw new SolrServerException(e); } catch (IOException e) { throw new SolrServerException(e); } finally { method.releaseConnection(); if (is != null) { is.close(); } } }