/** * 鍙栧緱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; }
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; }
/** * Attempt to POST contents of support request form to {@link #requestUrl}. * * @throws WrapperException if there was a problem on the server. */ protected String compute() { // logic ripped from the IDV's HttpFormEntry#doPost(List, String) try { while ((tryCount++ < POST_ATTEMPTS) && !isCancelled()) { method = buildPostMethod(validFormUrl, form); HttpClient client = new HttpClient(); client.executeMethod(method); if (method.getStatusCode() >= 300 && method.getStatusCode() <= 399) { Header location = method.getResponseHeader("location"); if (location == null) { return "Error: No 'location' given on the redirect"; } validFormUrl = location.getValue(); if (method.getStatusCode() == 301) { logger.warn("form post has been permanently moved to: {}", validFormUrl); } continue; } break; } return IOUtil.readContents(method.getResponseBodyAsStream()); } catch (Exception e) { throw new WrapperException(POST_ERROR, e); } }
/** * 执行一个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; }
@Test public void testPOSTObjectFormUrlEncoded() throws Exception { final String TAG_VALUE = "TAG"; NameValuePair[] nameValuePairs = new NameValuePair[2]; nameValuePairs[0] = new NameValuePair("className", "XWiki.TagClass"); nameValuePairs[1] = new NameValuePair("property#tags", TAG_VALUE); PostMethod postMethod = executePostForm( getUriBuilder(ObjectsResource.class).build(getWiki(), "Main", "WebHome").toString(), nameValuePairs, "Admin", "admin"); Assert.assertEquals( getHttpMethodInfo(postMethod), HttpStatus.SC_CREATED, postMethod.getStatusCode()); Object object = (Object) unmarshaller.unmarshal(postMethod.getResponseBodyAsStream()); Assert.assertEquals(TAG_VALUE, getProperty(object, "tags").getValue()); GetMethod getMethod = executeGet( getUriBuilder(ObjectResource.class) .build(getWiki(), "Main", "WebHome", object.getClassName(), object.getNumber()) .toString()); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); object = (Object) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream()); Assert.assertEquals(TAG_VALUE, getProperty(object, "tags").getValue()); }
@Override @Before public void setUp() throws Exception { super.setUp(); GetMethod getMethod = executeGet( getUriBuilder(PageResource.class).build(getWiki(), "Main", "WebHome").toString()); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); Page page = (Page) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream()); Link link = getFirstLinkByRelation(page, Relations.OBJECTS); /* Create a tag object if it doesn't exist yet */ if (link == null) { Object object = objectFactory.createObject(); object.setClassName("XWiki.TagClass"); PostMethod postMethod = executePostXml( getUriBuilder(ObjectsResource.class).build(getWiki(), "Main", "WebHome").toString(), object, "Admin", "admin"); Assert.assertEquals( getHttpMethodInfo(postMethod), HttpStatus.SC_CREATED, postMethod.getStatusCode()); } }
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."); } }
/** 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); }
/** * Method responsible for querying and parsing to correios cep locator * * @author pulu - 09/09/2013 */ private Webservicecep findAddressByCepAtCorreios(String url) throws IOException { HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url); log.log(Level.INFO, "Querying to correios WS..."); try { httpClient.executeMethod(postMethod); if (postMethod.getStatusCode() == HttpStatus.SC_OK) { Document doc = Jsoup.parse(new URL(url).openStream(), "ISO-8859-1", url); Elements elements = doc.select("td:not([colspan]):not(:has(*))"); return new Webservicecep( Webservicecep.SUCCESS_CODE, elements.get(3).ownText(), elements.get(2).ownText(), elements.get(1).ownText(), "", elements.get(0).ownText()); } else return new Webservicecep(Webservicecep.ERROR_CODE); } catch (Exception e) { log.log(Level.WARNING, "Failed to parse html data. Possible reason: invalid cep."); return new Webservicecep(Webservicecep.ERROR_CODE); } }
@Test public void testPOSTObject() throws Exception { final String TAG_VALUE = "TAG"; Property property = new Property(); property.setName("tags"); property.setValue(TAG_VALUE); Object object = objectFactory.createObject(); object.setClassName("XWiki.TagClass"); object.getProperties().add(property); PostMethod postMethod = executePostXml( getUriBuilder(ObjectsResource.class).build(getWiki(), "Main", "WebHome").toString(), object, "Admin", "admin"); Assert.assertEquals( getHttpMethodInfo(postMethod), HttpStatus.SC_CREATED, postMethod.getStatusCode()); object = (Object) unmarshaller.unmarshal(postMethod.getResponseBodyAsStream()); Assert.assertEquals(TAG_VALUE, getProperty(object, "tags").getValue()); GetMethod getMethod = executeGet( getUriBuilder(ObjectResource.class) .build(getWiki(), "Main", "WebHome", object.getClassName(), object.getNumber()) .toString()); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); object = (Object) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream()); Assert.assertEquals(TAG_VALUE, getProperty(object, "tags").getValue()); }
/** * 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; }
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 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(); } }
protected JSONObject postQuery(HttpClient httpClient, String url, JSONObject body) throws UnsupportedEncodingException, IOException, HttpException, URIException, JSONException { PostMethod post = new PostMethod(url); if (body.toString().length() > DEFAULT_SAVEPOST_BUFFER) { post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); } post.setRequestEntity( new ByteArrayRequestEntity(body.toString().getBytes("UTF-8"), "application/json")); try { httpClient.executeMethod(post); if (post.getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY || post.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { Header locationHeader = post.getResponseHeader("location"); if (locationHeader != null) { String redirectLocation = locationHeader.getValue(); post.setURI(new URI(redirectLocation, true)); httpClient.executeMethod(post); } } if (post.getStatusCode() != HttpServletResponse.SC_OK) { throw new LuceneQueryParserException( "Request failed " + post.getStatusCode() + " " + url.toString()); } Reader reader = new BufferedReader( new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet())); // TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler JSONObject json = new JSONObject(new JSONTokener(reader)); if (json.has("status")) { JSONObject status = json.getJSONObject("status"); if (status.getInt("code") != HttpServletResponse.SC_OK) { throw new LuceneQueryParserException("SOLR side error: " + status.getString("message")); } } return json; } finally { post.releaseConnection(); } }
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; }
/** * @param server * @param username * @param password */ private static String getTicketGrantingTicket( final String server, final String username, final String password) { final HttpClient client = new HttpClient(); final PostMethod post = new PostMethod(server); post.setRequestBody( new NameValuePair[] { new NameValuePair("username", username), new NameValuePair("password", password) }); try { client.executeMethod(post); final String response = post.getResponseBodyAsString(); info("TGT=" + response); switch (post.getStatusCode()) { case 201: { final Matcher matcher = Pattern.compile(".*action=\".*/(.*?)\".*").matcher(response); if (matcher.matches()) return matcher.group(1); warning("Successful ticket granting request, but no ticket found!"); info("Response (1k): " + response.substring(0, Math.min(1024, response.length()))); break; } 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; }
@Test public void testPUTObjectFormUrlEncoded() throws Exception { final String TAG_VALUE = UUID.randomUUID().toString(); Object objectToBePut = getObject("XWiki.TagClass"); GetMethod getMethod = executeGet( getUriBuilder(ObjectResource.class) .build( getWiki(), "Main", "WebHome", objectToBePut.getClassName(), objectToBePut.getNumber()) .toString()); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); Object object = (Object) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream()); NameValuePair[] nameValuePairs = new NameValuePair[1]; nameValuePairs[0] = new NameValuePair("property#tags", TAG_VALUE); PostMethod postMethod = executePostForm( String.format( "%s?method=PUT", getUriBuilder(ObjectResource.class) .build( getWiki(), "Main", "WebHome", objectToBePut.getClassName(), objectToBePut.getNumber()) .toString()), nameValuePairs, "Admin", "admin"); Assert.assertEquals( getHttpMethodInfo(postMethod), HttpStatus.SC_ACCEPTED, postMethod.getStatusCode()); Object updatedObjectSummary = (Object) unmarshaller.unmarshal(postMethod.getResponseBodyAsStream()); Assert.assertEquals(TAG_VALUE, getProperty(updatedObjectSummary, "tags").getValue()); Assert.assertEquals(object.getClassName(), updatedObjectSummary.getClassName()); Assert.assertEquals(object.getNumber(), updatedObjectSummary.getNumber()); }
/** Test that the body can be set as a String without an explict content type */ public void testStringBodyToBodyServlet() throws Exception { PostMethod method = new PostMethod("/"); String stringBody = "pname1=pvalue1&pname2=pvalue2"; method.setRequestEntity(new StringRequestEntity(stringBody, null, null)); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals("pname1=pvalue1&pname2=pvalue2", body); } finally { method.releaseConnection(); } }
/** Test that parameters can be added. */ public void testAddParametersToParamServlet() throws Exception { PostMethod method = new PostMethod("/"); method.addParameter(new NameValuePair("pname1", "pvalue1")); method.addParameter(new NameValuePair("pname2", "pvalue2")); this.server.setHttpService(new EchoService()); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String body = method.getResponseBodyAsString(); assertEquals("pname1=pvalue1&pname2=pvalue2", body); } finally { method.releaseConnection(); } }
private boolean checkLoginResult(PostMethod postMethod) throws IOException { int statusCode = postMethod.getStatusCode(); if (statusCode == HttpStatus.SC_NOT_FOUND) { myJira4 = false; return false; } if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_MOVED_TEMPORARILY) { throw new IOException( "Can't login: "******" (" + HttpStatus.getStatusText(statusCode) + ")"); } if (statusCode == HttpStatus.SC_OK && new String(postMethod.getResponseBody(2000)).contains("\"loginSucceeded\":false")) { throw new IOException(LOGIN_FAILED_CHECK_YOUR_PERMISSIONS); } return true; }
@POST @Path("stop/id/{id}") public Response stopContainerInfoByid(@PathParam("id") int id) throws HibernateException { try { System.out.println("hello"); String queryString = "from Container where id=?"; beginTransaction(); Query query = session.createQuery(queryString); query.setParameter(0, id); List<model.Container> containers = query.list(); String Containerid = containers.get(0).getContainerId(); // Containerid="7fe7f250c7f9/stop" String testUrlString = "http://" + Global.swarm_ip + ":" + Global.swarm_port + "/containers/" + Containerid + "/stop?t=5"; System.out.println("url" + testUrlString); HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(testUrlString); httpClient.executeMethod(postMethod); int StatusCode = postMethod.getStatusCode(); String mes = ""; System.out.println("get status code"); if (StatusCode == 204) { mes = "stop container successfully"; } if (StatusCode == 304) { mes = "container already stopped"; } if (StatusCode == 404) { mes = "no such container"; } if (StatusCode == 500) { mes = "server error"; } // ObjectMapper mapper = new ObjectMapper(); return ParseToReponse.parse("1", mes, StatusCode, 0); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); return ParseToReponse.parse("2", e.getMessage(), null, 0); } }
/** * Test that {@link PostMethod#addParameter(java.lang.String,java.lang.String)} and {@link * PostMethod#setQueryString(java.lang.String)} combine properly. */ public void testPostMethodParameterAndQueryString() throws Exception { this.server.setHttpService(new QueryInfoService()); PostMethod method = new PostMethod("/"); method.setQueryString("query=string"); method.setRequestBody( new NameValuePair[] { new NameValuePair("param", "eter"), new NameValuePair("para", "meter") }); try { this.client.executeMethod(method); assertEquals(200, method.getStatusCode()); String response = method.getResponseBodyAsString(); assertTrue(response.indexOf("QueryString=\"query=string\"") >= 0); assertFalse(response.indexOf("QueryString=\"param=eter¶=meter\"") >= 0); } finally { method.releaseConnection(); } }
@Test public void testPOSTObjectNotAuthorized() throws Exception { final String TAG_VALUE = "TAG"; Property property = new Property(); property.setName("tags"); property.setValue(TAG_VALUE); Object object = objectFactory.createObject(); object.setClassName("XWiki.TagClass"); object.getProperties().add(property); PostMethod postMethod = executePostXml( getUriBuilder(ObjectsResource.class).build(getWiki(), "Main", "WebHome").toString(), object); Assert.assertEquals( getHttpMethodInfo(postMethod), HttpStatus.SC_UNAUTHORIZED, postMethod.getStatusCode()); }
public static String httpClientPost(String url) { String response = null; 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(); } return response; }
/** Test that the body consisting of a string part can be posted. */ public void testPostStringPart() throws Exception { this.server.setHttpService(new EchoService()); PostMethod method = new PostMethod(); MultipartRequestEntity entity = new MultipartRequestEntity( new Part[] {new StringPart("param", "Hello", "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=\"param\"") >= 0); assertTrue(body.indexOf("Content-Type: text/plain; charset=ISO-8859-1") >= 0); assertTrue(body.indexOf("Content-Transfer-Encoding: 8bit") >= 0); assertTrue(body.indexOf("Hello") >= 0); }
@Test public void testPOSTInvalidObject() throws Exception { final String TAG_VALUE = "TAG"; Property property = new Property(); property.setName("tags"); property.setValue(TAG_VALUE); Object object = objectFactory.createObject(); object.getProperties().add(property); PostMethod postMethod = executePostXml( getUriBuilder(ObjectsResource.class).build(getWiki(), "Main", "WebHome").toString(), object, "Admin", "admin"); Assert.assertEquals( getHttpMethodInfo(postMethod), HttpStatus.SC_BAD_REQUEST, postMethod.getStatusCode()); }
@Override public void updateTimeSpent(final LocalTask task, final String timeSpent, final String comment) throws Exception { final HttpClient client = login(); checkVersion(client); PostMethod method = new PostMethod(getUrl() + "/rest/api/2/issue/" + task.getId() + "/worklog"); method.setRequestEntity( new StringRequestEntity( "{\"timeSpent\" : \"" + timeSpent + "\"" + (StringUtil.isNotEmpty(comment) ? ", \"comment\" : " + comment : "") + " }", "application/json", "UTF-8")); client.executeMethod(method); if (method.getStatusCode() != 201) { throw new Exception(method.getResponseBodyAsString()); } }
private Object getObject(String className) throws Exception { GetMethod getMethod = executeGet( getUriBuilder(ObjectsResource.class).build(getWiki(), "Main", "WebHome").toString()); Assert.assertEquals(getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); Objects objects = (Objects) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream()); Assert.assertFalse(objects.getObjectSummaries().isEmpty()); for (ObjectSummary objectSummary : objects.getObjectSummaries()) { if (objectSummary.getClassName().equals(className)) { Link link = getFirstLinkByRelation(objectSummary, Relations.OBJECT); Assert.assertNotNull(link); getMethod = executeGet(link.getHref()); Assert.assertEquals( getHttpMethodInfo(getMethod), HttpStatus.SC_OK, getMethod.getStatusCode()); Object object = (Object) unmarshaller.unmarshal(getMethod.getResponseBodyAsStream()); return object; } } /* If no object of that class is found, then create a new one */ Object object = objectFactory.createObject(); object.setClassName(className); PostMethod postMethod = executePostXml( getUriBuilder(ObjectsResource.class).build(getWiki(), "Main", "WebHome").toString(), object, "Admin", "admin"); Assert.assertEquals( getHttpMethodInfo(postMethod), HttpStatus.SC_CREATED, postMethod.getStatusCode()); object = (Object) unmarshaller.unmarshal(postMethod.getResponseBodyAsStream()); return object; }
public static void postSolrDoc(InputStream content, String updateUrl) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(content, baos); content.close(); PostMethod post = new PostMethod(updateUrl); Part[] parts = { new FilePart( "add.xml", new ByteArrayPartSource("add.xml", baos.toByteArray()), "text/xml", "UTF-8") }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); try { new HttpClient().executeMethod(post); int status = post.getStatusCode(); if (status != HttpStatus.SC_OK) { throw new RuntimeException( "REST action \"" + updateUrl + "\" failed: " + post.getStatusLine()); } } finally { post.releaseConnection(); } }
/** * 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()); } } }