List of usage examples for org.apache.commons.httpclient NameValuePair NameValuePair
public NameValuePair(String name, String value)
From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java
public String obtainClientCredentialsAccessTokenResponse(String currentClientId, String currentClientSecret, String scope, boolean addAuthHeader) { PostMethod post = new PostMethod(baseOAuth20Uri + TOKEN_ENDPOINT); String response = null;// w w w. jav a2 s . co m try { post.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); if (addAuthHeader) { NameValuePair[] requestBody = { new NameValuePair(GRANT_TYPE_PARAM, GRANT_TYPE_CLIENT_CREDENTIALS), new NameValuePair(SCOPE_PARAM, scope) }; post.setRequestBody(requestBody); post.setRequestHeader(HttpHeaders.AUTHORIZATION, createBasicAuthorization(currentClientId, currentClientSecret)); } else { NameValuePair[] requestBody = { new NameValuePair(GRANT_TYPE_PARAM, GRANT_TYPE_CLIENT_CREDENTIALS), new NameValuePair(SCOPE_PARAM, scope), new NameValuePair(CLIENT_ID_PARAM, currentClientId), new NameValuePair(CLIENT_SECRET_PARAM, currentClientSecret) }; post.setRequestBody(requestBody); } response = readResponse(post); } catch (IOException e) { log.error("cannot obtain client credentials acces token response", e); } return response; }
From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java
/** * Sets up the given {@link PostMethod} to send the same standard POST * data as was sent in the given {@link HttpServletRequest} * * @param postMethodProxyRequest The {@link PostMethod} that we are * configuring to send a standard POST request * @param httpServletRequest The {@link HttpServletRequest} that contains * the POST data to be sent via the {@link PostMethod} *///from w ww . ja v a 2 s .c om @SuppressWarnings({ "unchecked", "ToArrayCallWithZeroLengthArrayArgument" }) private void handleStandardPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) { // Get the client POST data as a Map Map<String, String[]> mapPostParameters = (Map<String, String[]>) httpServletRequest.getParameterMap(); // Create a List to hold the NameValuePairs to be passed to the PostMethod List<NameValuePair> listNameValuePairs = new ArrayList<NameValuePair>(); // Iterate the parameter names for (String stringParameterName : mapPostParameters.keySet()) { // Iterate the values for each parameter name String[] stringArrayParameterValues = mapPostParameters.get(stringParameterName); for (String stringParamterValue : stringArrayParameterValues) { // Create a NameValuePair and store in list NameValuePair nameValuePair = new NameValuePair(stringParameterName, stringParamterValue); listNameValuePairs.add(nameValuePair); } } // Set the proxy request POST data postMethodProxyRequest.setRequestBody(listNameValuePairs.toArray(new NameValuePair[] {})); }
From source file:com.cloudmade.api.CMClient.java
/** * Find route between two points with given paramteres. * //w w w .j a va 2 s . c om * @param start Starting point * @param end Ending point * @param routeType Type of route, e.g. car, foot, etc. * @param transitPoints List of points route must visit before * reaching end. Points are visited in the same order they are * specified in the sequence. Set it to <code>null</code> if you do not need it. * @param typeModifier Modifier of the route type, e.g. shortest * @param lang Language code in conference to `ISO 3166-1 alpha-2` standard * @param units Measure units for distance calculation (km/miles) * @return Route that was found * @throws OpenStreetMapRouteNotFoundException If no route found between points. */ public Route route(Point start, Point end, RouteType routeType, List<Point> transitPoints, RouteTypeModifier typeModifier, String lang, MeasureUnit units) throws OpenStreetMapRouteNotFoundException { byte[] response = {}; try { StringBuffer tps = new StringBuffer(""); if (transitPoints != null && transitPoints.size() > 0) { tps.append("["); for (Point transitPoint : transitPoints) { tps.append(transitPoint.toString()).append(","); } tps.replace(tps.length() - 1, tps.length(), "],"); } String tms = ""; if (typeModifier != null) { tms = "/" + typeModifier.name; } String uri = String.format(Locale.US, "/api/0.3/%s,%s%s/%s%s.js", start.toString(), URLEncoder.encode(tps.toString(), "utf-8"), end.toString(), routeType.name, tms); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("lang", lang)); params.add(new NameValuePair("units", units.name)); response = callService(uri, "routes", params.toArray(new NameValuePair[0])); JSONObject obj = new JSONObject(new String(response, "UTF-8")); return Utils.routeFromJson(obj); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
From source file:com.clarkparsia.sbol.editor.sparql.StardogEndpoint.java
@Override public void validate(RDFInput constraints, String namedGraph) throws Exception { RequestEntity entity = createEntity(constraints); PostMethod post = new PostMethod(url + "/icv/violations"); if (namedGraph != null) { post.setQueryString(new NameValuePair[] { new NameValuePair("graph-uri", namedGraph) }); }//from ww w . j a va 2s . co m post.setRequestEntity(entity); execute(post); ByteStreams.copy(post.getResponseBodyAsStream(), System.out); }
From source file:edu.uci.ics.pregelix.example.util.TestExecutor.java
private InputStream getHandleResult(String handle, OutputFormat fmt) throws Exception { final String url = "http://localhost:19002/query/result"; // Create a method instance. GetMethod method = new GetMethod(url); method.setQueryString(new NameValuePair[] { new NameValuePair("handle", handle) }); method.setRequestHeader("Accept", fmt.mimeType()); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); executeHttpMethod(method);//w w w . ja v a2 s .c o m return method.getResponseBodyAsStream(); }
From source file:edu.harvard.iq.dvn.core.web.dvnremote.DvnTermsOfUseAccess.java
public String dvnAcceptRemoteTOU(String TOUurl, String jsessionid, String downloadURL, String extraCookies) { GetMethod TOUgetMethod = null;//w w w .j a va 2s.c o m PostMethod TOUpostMethod = null; GetMethod redirectGetMethod = null; String compatibilityPrefix = ""; Boolean compatibilityMode = false; Matcher matcher = null; String remotehosturl = null; String remotehost = null; String regexpRemoteHostURL = "(https*://[^/]*/)"; Pattern patternRemoteHostURL = Pattern.compile(regexpRemoteHostURL); if (downloadURL != null) { matcher = patternRemoteHostURL.matcher(downloadURL); if (matcher.find()) { remotehosturl = matcher.group(1); dbgLog.fine("TOU found remote url: " + remotehosturl); } } try { TOUgetMethod = new GetMethod(TOUurl); if (jsessionid != null) { TOUgetMethod.addRequestHeader("Cookie", "JSESSIONID=" + jsessionid); } else { // Do we have a cached jsessionid? String cachedJsessionID = null; if (remotehosturl != null) { String regexpRemoteHost = "https*://([^/]*)/"; Pattern patternRemoteHost = Pattern.compile(regexpRemoteHost); matcher = patternRemoteHost.matcher(remotehosturl); if (matcher.find()) { remotehost = matcher.group(1); cachedJsessionID = getCachedJsessionID(remotehost); if (cachedJsessionID != null) { TOUgetMethod.addRequestHeader("Cookie", "JSESSIONID=" + cachedJsessionID); jsessionid = cachedJsessionID; } } } } if (extraCookies != null) { TOUgetMethod.addRequestHeader("Cookie", extraCookies); } String icesession = null; String iceview = null; String facesviewstate = null; String studyid = null; String remotefileid = null; String iceFacesUpdate = null; /* * As of DVN 3.0 (and IceFaces 3.*), the following has changed: * icesession - no longer used; * ice.window - appears to have replaced the above; * the old regex pattern for ViewState no longer works (see below); * in fact, javax.faces.ViewState and ice.view must be * treated as separate parameters! (again, see below) * (the last one needs to be verified; there's a chance that * javax.faces.ViewState is still not necessary... -- L.A.) * * TODO: add re-test with DVN 2.* and make sure backward compatibility * mechanism is in place. -- L.A. * */ String regexpRemoteFileId = "(/FileDownload.*)"; String regexpJsession = "JSESSIONID=([^;]*);"; /* old ice.session; no longer used in 3.0: String regexpIceSession = "session: \'([^\']*)\'"; */ /* ice.window, appears to have replaced ice.session above: */ String regexpIceSession = "input [^>]*ice.window\"[^>]*value=\"([^\"]*)\""; /* ice.view pattern, changed: String regexpIceViewState = "view: ([^,]*),"; */ String regexpIceViewState = "<input [^>]*ice.view\"[^>]*value=\"([^\"]*)\""; /* New in DVN/IceFaces 3.*: separate pattern of javax.faces.ViewState: */ String regexpFacesViewState = "<input [^>]*ViewState\"[^>]*value=\"([^\"]*)\""; String regexpStudyId = "studyId\"[^>]*value=\"([0-9]*)\""; //String regexpRemoteFileId = "(/FileDownload.*fileId=[0-9]*)"; String regexpOldStyleForm = "content:termsOfUsePageView:"; Pattern patternJsession = Pattern.compile(regexpJsession); Pattern patternRemoteFileId = Pattern.compile(regexpRemoteFileId); Pattern patternIceSession = Pattern.compile(regexpIceSession); Pattern patternIceViewState = Pattern.compile(regexpIceViewState); Pattern patternFacesViewState = Pattern.compile(regexpFacesViewState); Pattern patternStudyId = Pattern.compile(regexpStudyId); Pattern patternOldStyleForm = Pattern.compile(regexpOldStyleForm); int status = getClient().executeMethod(TOUgetMethod); for (int i = 0; i < TOUgetMethod.getResponseHeaders().length; i++) { String headerName = TOUgetMethod.getResponseHeaders()[i].getName(); //dbgLog.info("TOU found header: "+headerName); if (headerName.equals("Set-Cookie")) { String cookieHeader = TOUgetMethod.getResponseHeaders()[i].getValue(); dbgLog.fine("TOU found cookie header: " + cookieHeader); matcher = patternJsession.matcher(cookieHeader); if (matcher.find()) { jsessionid = matcher.group(1); dbgLog.fine("TOU - jsessionid issued (as a cookie): " + jsessionid); // TODO: // Any scenarios where we would want to cache it here? // -L.A. } } } InputStream in = TOUgetMethod.getResponseBodyAsStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(in)); String line = null; if (downloadURL != null) { matcher = patternRemoteFileId.matcher(downloadURL); if (matcher.find()) { remotefileid = matcher.group(1); dbgLog.fine("TOU found remotefileid: " + remotefileid); } if (remotehosturl != null) { // The update URL, below, only works with IceFaces < 2.0, // i.e., only if the remote DVN is v2.*: //iceFacesUpdate = remoteurl + "dvn/block/send-receive-updates"; // For IceFaces and DVN 3.*, the POST must be submitted to // the terms of use page itself: // (needs to be verified -- L.A.) iceFacesUpdate = remotehosturl + "dvn/faces/study/TermsOfUsePage.xhtml"; } } while ((line = rd.readLine()) != null) { matcher = patternIceSession.matcher(line); if (matcher.find()) { icesession = matcher.group(1); dbgLog.fine("TOU found icesession: " + icesession); } matcher = patternIceViewState.matcher(line); if (matcher.find()) { iceview = matcher.group(1); dbgLog.fine("TOU found ice view: " + iceview); } matcher = patternFacesViewState.matcher(line); if (matcher.find()) { facesviewstate = matcher.group(1); dbgLog.fine("TOU found faces view state: " + facesviewstate); } matcher = patternStudyId.matcher(line); if (matcher.find()) { studyid = matcher.group(1); dbgLog.fine("TOU found study id: " + studyid); } if (!compatibilityMode) { matcher = patternOldStyleForm.matcher(line); if (matcher.find()) { compatibilityMode = true; } } } //if ( compatibilityMode ) { // compatibilityPrefix = "content:termsOfUsePageView:"; //} rd.close(); TOUgetMethod.releaseConnection(); if (jsessionid != null) { // We have either been issued a new JSESSIONID, or had one // cached for this host, or // already had a JSESSIONID issued // to us when we logged in. Either way we can // now make the final call agreeing to // to the Terms of Use; // it has to be a POST method: TOUpostMethod = new PostMethod(iceFacesUpdate); //TOUurl = TOUurl.substring(0, TOUurl.indexOf( "?" )); //TOUpostMethod = new PostMethod( TOUurl + ";jsessionid=" + jsessionid ); dbgLog.fine("icefaces url: " + iceFacesUpdate); TOUpostMethod.addRequestHeader("Cookie", "JSESSIONID=" + jsessionid); if (extraCookies != null) { TOUpostMethod.addRequestHeader("Cookie", extraCookies); } TOUpostMethod.setFollowRedirects(false); NameValuePair[] postParameters = { /* new in 3.0: ViewState different from ice.view: */ new NameValuePair("javax.faces.ViewState", facesviewstate), /* new in 3.0: no longer necessary: new NameValuePair( "javax.faces.RenderKitId", "ICEfacesRenderKit" ), */ /* new in 3.0: no longer necessary: new NameValuePair( "ice.submit.partial", "false" ), */ new NameValuePair("icefacesCssUpdates", ""), /* new in 3.0: ice.window instead of icesession: */ new NameValuePair("ice.window", icesession), /* new in 3.0: ice.view different from viewstate: */ new NameValuePair("ice.view", iceview), new NameValuePair("ice.focus", "form1:termsButton"), new NameValuePair("pageName", "TermsOfUsePage"), new NameValuePair("form1", "form1"), new NameValuePair("form1:vdcId", ""), new NameValuePair("form1:studyId", studyid), new NameValuePair("form1:redirectPage", remotefileid), new NameValuePair("form1:tou", "download"), new NameValuePair("form1:termsAccepted", "on"), new NameValuePair("form1:termsButton", "Continue") }; // TODO: // no need to set the redirectPage parameter, if there's // no filedownload url. TOUpostMethod.setRequestBody(postParameters); status = getClient().executeMethod(TOUpostMethod); dbgLog.fine("TOU Post status: " + status); // Now the TOU system is going to redirect // us to the actual download URL. // Note that it can be MORE THAN ONE // redirects (first to the homepage, then // eventually to the file download url); // So we want to just keep following the // redirect until we get the file. // But just in case, we'll be counting the // redirect hoops to make sure we're not // stuck in a loop. String redirectLocation = null; if (status == 302) { for (int i = 0; i < TOUpostMethod.getResponseHeaders().length; i++) { String headerName = TOUpostMethod.getResponseHeaders()[i].getName(); if (headerName.equals("Location")) { redirectLocation = TOUpostMethod.getResponseHeaders()[i].getValue(); } } } else if (status == 200) { for (int i = 0; i < TOUpostMethod.getResponseHeaders().length; i++) { String headerName = TOUpostMethod.getResponseHeaders()[i].getName(); dbgLog.fine("TOU post header: " + headerName + "=" + TOUpostMethod.getResponseHeaders()[i].getValue()); } dbgLog.fine("TOU trying to read output of the post method;"); InputStream pin = TOUpostMethod.getResponseBodyAsStream(); BufferedReader prd = new BufferedReader(new InputStreamReader(pin)); String pline = null; while ((pline = prd.readLine()) != null) { dbgLog.fine("TOU read line: " + pline); } prd.close(); } TOUpostMethod.releaseConnection(); int counter = 0; while (status == 302 && counter < 10 && (!(redirectLocation.matches(".*FileDownload.*")))) { redirectGetMethod = new GetMethod(redirectLocation); redirectGetMethod.setFollowRedirects(false); redirectGetMethod.addRequestHeader("Cookie", "JSESSIONID=" + jsessionid); if (extraCookies != null) { redirectGetMethod.addRequestHeader("Cookie", extraCookies); } status = getClient().executeMethod(redirectGetMethod); if (status == 302) { for (int i = 0; i < redirectGetMethod.getResponseHeaders().length; i++) { String headerName = redirectGetMethod.getResponseHeaders()[i].getName(); if (headerName.equals("Location")) { redirectLocation = redirectGetMethod.getResponseHeaders()[i].getValue(); } } } redirectGetMethod.releaseConnection(); counter++; } } } catch (IOException ex) { if (redirectGetMethod != null) { redirectGetMethod.releaseConnection(); } if (TOUgetMethod != null) { TOUgetMethod.releaseConnection(); } if (TOUpostMethod != null) { TOUpostMethod.releaseConnection(); } return null; } dbgLog.fine("TOU: returning jsessionid=" + jsessionid); return jsessionid; }
From source file:hu.sztaki.lpds.pgportal.services.dspace.LNIclient.java
/** * Set up and initiate the PUT method, but leave the actual * technique of writing the request body to the caller. *///from w ww . j a v a 2s . c o m private void startPutInternal(String collection, String type, NameValuePair options[], InputStream is) throws IOException, HttpException { if (lastPut != null) throw new IOException("Bad state: startPUT called twice without finishPUT."); String url = lookupHandle(collection); NameValuePair args[] = new NameValuePair[1 + (options == null ? 0 : options.length)]; args[0] = new NameValuePair("package", type); if (options != null) { for (int i = 0; i < options.length; ++i) args[i + 1] = options[i]; } lastPut = new PutMethod(url); lastPut.setDoAuthentication(true); lastPut.setQueryString(args); lastPut.setRequestEntity(new InputStreamRequestEntity(is, -1)); }
From source file:edu.ku.brc.util.WebStoreAttachmentMgr.java
@Override public Calendar getFileEmbeddedDate(final int attachmentID) { String dateStr = null;/* w ww .j av a2s. c o m*/ String fileName = BasicSQLUtils.querySingleObj(ATTACHMENT_URL + attachmentID); if (StringUtils.isNotEmpty(fileName) && StringUtils.isNotEmpty(fileGetMetaDataURLStr)) { GetMethod method = new GetMethod(fileGetMetaDataURLStr); fillValuesArray(); method.setQueryString(new NameValuePair[] { new NameValuePair("dt", "json"), new NameValuePair("filename", fileName), new NameValuePair("token", generateToken(fileName)), new NameValuePair("coll", values[0]), new NameValuePair("disp", values[1]), new NameValuePair("div", values[2]), new NameValuePair("inst", values[3]) }); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(5000); try { int status = client.executeMethod(method); updateServerTimeDelta(method); if (status == HttpStatus.SC_OK) { dateStr = method.getResponseBodyAsString(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { method.releaseConnection(); } } if (dateStr != null && dateStr.length() == 10) { try { Date convertedDate = dateFormat.parse(dateStr); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(convertedDate.getTime()); return cal; } catch (ParseException e) { e.printStackTrace(); } } return null; }
From source file:edu.ku.brc.af.tasks.StatsTrackerTask.java
/** * Creates an array of POST method parameters to send with the version checking / usage tracking connection. * /* w w w .java 2 s . c o m*/ * @param doSendSecondaryStats if true, the POST parameters include usage stats * @return an array of POST parameters */ protected Vector<NameValuePair> createPostParameters(final boolean doSendSecondaryStats) { Vector<NameValuePair> postParams = new Vector<NameValuePair>(); try { // get the install ID String installID = UsageTracker.getInstallId(); postParams.add(new NameValuePair("id", installID)); //$NON-NLS-1$ //get ISA number Collection collection = AppContextMgr.getInstance().hasContext() ? AppContextMgr.getInstance().getClassObject(Collection.class) : null; String isaNumber = collection == null ? "N/A" : collection.getIsaNumber(); try { postParams.add(new NameValuePair("ISA_number", isaNumber)); //$NON-NLS-1$ } catch (NullPointerException e) { } // get the OS name and version postParams.add(new NameValuePair("os_name", System.getProperty("os.name"))); //$NON-NLS-1$ postParams.add(new NameValuePair("os_version", System.getProperty("os.version"))); //$NON-NLS-1$ postParams.add(new NameValuePair("java_version", System.getProperty("java.version"))); //$NON-NLS-1$ postParams.add(new NameValuePair("java_vendor", System.getProperty("java.vendor"))); //$NON-NLS-1$ //if (!UIRegistry.isRelease()) // For Testing Only { postParams.add(new NameValuePair("user_name", System.getProperty("user.name"))); //$NON-NLS-1$ try { postParams.add(new NameValuePair("ip", InetAddress.getLocalHost().getHostAddress())); //$NON-NLS-1$ } catch (UnknownHostException e) { } } postParams.add(new NameValuePair("tester", //$NON-NLS-1$ AppPreferences.getLocalPrefs().getBoolean("tester", false) ? "true" : "false")); String resAppVersion = UIRegistry.getAppVersion(); if (StringUtils.isEmpty(resAppVersion)) { resAppVersion = "Unknown"; } postParams.add(new NameValuePair("app_version", resAppVersion)); //$NON-NLS-1$ Vector<NameValuePair> extraStats = collectSecondaryStats(doSendSecondaryStats); if (extraStats != null) { postParams.addAll(extraStats); } // get all of the usage tracking stats List<Pair<String, Integer>> statistics = UsageTracker.getUsageStats(); for (Pair<String, Integer> stat : statistics) { postParams.add(new NameValuePair(stat.first, Integer.toString(stat.second))); } return postParams; } catch (Exception ex) { ex.printStackTrace(); edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(StatsTrackerTask.class, ex); } return null; }
From source file:com.sammyun.plugin.alipayWap.AlipayWapPlugin.java
/** * MAP??NameValuePair/*from w w w . jav a 2 s.c o m*/ * * @param properties MAP * @return NameValuePair */ private static NameValuePair[] generatNameValuePair(Map<String, Object> properties) { NameValuePair[] nameValuePair = new NameValuePair[properties.size()]; int i = 0; for (Map.Entry<String, Object> entry : properties.entrySet()) { nameValuePair[i++] = new NameValuePair(entry.getKey(), entry.getValue().toString()); } return nameValuePair; }