Java Code Examples for org.apache.http.message.BasicNameValuePair

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project android-async-http, under directory /src/com/loopj/android/http/.

Source file: RequestParams.java

  17 
vote

protected List<BasicNameValuePair> getParamsList(){
  List<BasicNameValuePair> lparams=new LinkedList<BasicNameValuePair>();
  for (  ConcurrentHashMap.Entry<String,String> entry : urlParams.entrySet()) {
    lparams.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
  }
  return lparams;
}
 

Example 2

From project android-bankdroid, under directory /src/com/liato/bankdroid/banking/banks/.

Source file: Avanza.java

  17 
vote

@Override protected LoginPackage preLogin() throws BankException, ClientProtocolException, IOException {
  urlopen=new Urllib(true,true);
  List<NameValuePair> postData=new ArrayList<NameValuePair>();
  postData.add(new BasicNameValuePair("username",username));
  postData.add(new BasicNameValuePair("password",password));
  return new LoginPackage(urlopen,postData,null,"https://www.avanza.se/aza/login/login.jsp");
}
 

Example 3

From project android-tether, under directory /src/og/android/tether/.

Source file: DeviceRegistrar.java

  17 
vote

private static HttpResponse makeRequest(Context context,String deviceRegistrationID,String urlPath) throws Exception {
  List<BasicNameValuePair> params=new ArrayList<BasicNameValuePair>();
  params.add(new BasicNameValuePair("c2dm_id",deviceRegistrationID));
  String aid=Secure.getString(context.getContentResolver(),Secure.ANDROID_ID);
  if (aid != null) {
    params.add(new BasicNameValuePair("aid",aid));
  }
  params.add(new BasicNameValuePair("device_type",isTablet(context) ? "Tablet" : "Phone"));
  return WebserviceTask.makeRequest(urlPath,params);
}
 

Example 4

From project androidquery, under directory /demo/src/com/androidquery/test/async/.

Source file: AjaxLoadingActivity.java

  17 
vote

public void async_post_entity() throws UnsupportedEncodingException {
  String url="http://search.twitter.com/search.json";
  List<NameValuePair> pairs=new ArrayList<NameValuePair>();
  pairs.add(new BasicNameValuePair("q","androidquery"));
  HttpEntity entity=new UrlEncodedFormEntity(pairs,"UTF-8");
  Map<String,Object> params=new HashMap<String,Object>();
  params.put(AQuery.POST_ENTITY,entity);
  aq.progress(R.id.progress).ajax(url,params,JSONObject.class,new AjaxCallback<JSONObject>(){
    @Override public void callback(    String url,    JSONObject json,    AjaxStatus status){
      showResult(json,status);
    }
  }
);
}
 

Example 5

From project androlog, under directory /androlog/src/main/java/de/akquinet/android/androlog/reporter/.

Source file: PostReporter.java

  17 
vote

public static void postReport(URL url,String param) throws IOException {
  HttpClient httpclient=new DefaultHttpClient();
  HttpPost httppost=new HttpPost(url.toExternalForm());
  try {
    List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("report",param));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    httpclient.execute(httppost);
  }
 catch (  ClientProtocolException e) {
    throw new IOException(e.getMessage());
  }
}
 

Example 6

From project api-sdk-java, under directory /api-sdk/src/main/java/com/smartling/api/sdk/file/.

Source file: FileApiClientAdapterImpl.java

  17 
vote

public StringResponse getFile(String fileUri,String locale,RetrievalType retrievalType) throws FileApiException {
  String params=buildParamsQuery(new BasicNameValuePair(FILE_URI,fileUri),new BasicNameValuePair(LOCALE,locale),new BasicNameValuePair(RETRIEVAL_TYPE,null == retrievalType ? null : retrievalType.name()));
  HttpGet getRequest=new HttpGet(buildUrl(GET_FILE_API_URL,params));
  StringResponse response=executeHttpcall(getRequest);
  return response;
}
 

Example 7

From project AudioBox.fm-JavaLib, under directory /audiobox.fm-core/src/main/java/fm/audiobox/core/models/.

Source file: MediaFile.java

  17 
vote

private boolean _destroy() throws ServiceException, LoginException {
  String path=IConnector.URI_SEPARATOR.concat(MediaFiles.NAMESPACE);
  List<NameValuePair> params=new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair(MediaFiles.TOKENS_PARAMETER,this.getToken()));
  Response response=this.getConnector(IConfiguration.Connectors.RAILS).delete(this,path,MediaFiles.Actions.multidestroy.toString(),params).send(false);
  return response.isOK();
}
 

Example 8

From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/goodreads/api/.

Source file: ReviewUpdateHandler.java

  17 
vote

public void update(long reviewId,boolean isRead,String readAt,String review,int rating) throws ClientProtocolException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, IOException, NotAuthorizedException, BookNotFoundException, NetworkException {
  HttpPost post=new HttpPost("http://www.goodreads.com/review/" + reviewId + ".xml");
  List<NameValuePair> parameters=new ArrayList<NameValuePair>();
  if (isRead)   parameters.add(new BasicNameValuePair("shelf","read"));
 else   parameters.add(new BasicNameValuePair("shelf","to-read"));
  if (review != null)   parameters.add(new BasicNameValuePair("review[review]",review));
  if (readAt != null && !readAt.equals(""))   parameters.add(new BasicNameValuePair("review[read_at]",readAt));
  if (rating >= 0)   parameters.add(new BasicNameValuePair("review[rating]",Integer.toString(rating)));
  post.setEntity(new UrlEncodedFormEntity(parameters,"UTF8"));
  mManager.execute(post,null,true);
}
 

Example 9

From project caustic, under directory /implementation/browser-apache/src/net/caustic/http/.

Source file: ApacheBrowser.java

  17 
vote

/** 
 * Private method, converts an array of AbstractHeaders to an UrlEncodedFormEntity.
 * @param headers.
 * @throws UnsupportedEncodingException If the Map contains a string that cannot be encoded.
 * @throws BrowserException 
 * @throws InterruptedException 
 * @throws MissingVariable 
 * @throws TemplateException 
 * @throws ResourceNotFoundException 
 */
private static UrlEncodedFormEntity generateFormEntity(AbstractResource[] headers,AbstractResult caller) throws UnsupportedEncodingException, ResourceNotFoundException, TemplateException, MissingVariable, BrowserException, InterruptedException {
  List<BasicNameValuePair> pairs=new ArrayList<BasicNameValuePair>();
  for (int i=0; i < headers.length; i++) {
    Result header=headers[i].getValue(caller)[0];
    pairs.add(new BasicNameValuePair(header.key,header.value));
  }
  return new UrlEncodedFormEntity(pairs);
}
 

Example 10

From project couchdb4j, under directory /src/java/com/fourspaces/couchdb/.

Source file: Update.java

  17 
vote

/** 
 * Add a key/value parameter to be passed to the document update handler function. Note that if  the key already exists, all instances of it will be removed prior to insertion.
 * @param key
 * @param value
 */
public void addParameter(String key,String value){
  if ((key == null) || (key.equals(""))) {
    return;
  }
  removeParameter(key);
  params.add(new BasicNameValuePair(key,value));
}
 

Example 11

From project cow, under directory /src/com/ad/cow/library/.

Source file: UserFunctions.java

  17 
vote

/** 
 * ??????? ??????????? ??????????? ????????????
 * @param email
 * @param password
 */
public JSONObject loginUser(String email,String password){
  List<NameValuePair> params=new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("tag",login_tag));
  params.add(new BasicNameValuePair("email",email));
  params.add(new BasicNameValuePair("password",password));
  JSONObject json=jsonParser.getJSONFromUrl(loginURL,params);
  return json;
}
 

Example 12

From project DiscogsForAndroid, under directory /src/com/discogs/services/.

Source file: Engine.java

  17 
vote

public void createFolder(String resourceUrl,String folderName){
  stringBuffer.setLength(0);
  stringBuffer.append(resourceUrl);
  List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(1);
  nameValuePairs.add(new BasicNameValuePair("name",folderName));
  try {
    String response=networkHelper.doHTTPPost(stringBuffer.toString(),nameValuePairs);
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 13

From project dreamDroid, under directory /src/net/reichholf/dreamdroid/fragment/abs/.

Source file: AbstractHttpFragment.java

  17 
vote

/** 
 * Called after a Button has been clicked
 * @param id The id of the item
 * @param longClick If true the item has been long-clicked
 */
@SuppressWarnings("unchecked") private void onVolumeButtonClicked(String set){
  ArrayList<NameValuePair> params=new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("set",set));
  if (mVolumeTask != null) {
    mVolumeTask.cancel(true);
  }
  mVolumeTask=new SetVolumeTask();
  mVolumeTask.execute(params);
}
 

Example 14

From project droidgiro-android, under directory /src/se/droidgiro/scanner/.

Source file: CaptureActivity.java

  17 
vote

private void sendInvoice(final Context context,final Invoice invoice){
  List<NameValuePair> fields=new ArrayList<NameValuePair>();
  if (invoice.isAmountDefined())   fields.add(new BasicNameValuePair("amount",invoice.getCompleteAmount()));
  if (invoice.isDocumentTypeDefined())   fields.add(new BasicNameValuePair("type",invoice.getType()));
  if (invoice.isGiroAccountDefined())   fields.add(new BasicNameValuePair("account",invoice.getGiroAccount()));
  if (invoice.isReferenceDefined())   fields.add(new BasicNameValuePair("reference",invoice.getReference()));
  if (fields.size() > 0)   sendFields(context,fields);
}
 

Example 15

From project droidkit, under directory /src/org/droidkit/net/ezhttp/.

Source file: EzHttpRequest.java

  17 
vote

public void addParam(String name,String value){
  if (mParams == null) {
    mParams=new ArrayList<NameValuePair>();
  }
  mParams.add(new BasicNameValuePair(name,value));
}
 

Example 16

From project fanfoudroid, under directory /src/com/ch_linghu/fanfoudroid/fanfou/.

Source file: Weibo.java

  17 
vote

/** 
 * Issues an HTTP GET request.
 * @param url the request url
 * @param name1 the name of the first parameter
 * @param value1 the value of the first parameter
 * @param name2 the name of the second parameter
 * @param value2 the value of the second parameter
 * @param authenticate if true, the request will be sent with BASIC authentication header
 * @return the response
 * @throws HttpException
 */
protected Response get(String url,String name1,String value1,String name2,String value2,boolean authenticate) throws HttpException {
  ArrayList<BasicNameValuePair> params=new ArrayList<BasicNameValuePair>();
  params.add(new BasicNameValuePair(name1,HttpClient.encode(value1)));
  params.add(new BasicNameValuePair(name2,HttpClient.encode(value2)));
  return get(url,params,authenticate);
}
 

Example 17

From project Fotolia-API, under directory /java/org/webservice/fotolia/.

Source file: FotoliaApi.java

  17 
vote

/** 
 * This method makes possible to search media in fotolia image bank. Full search capabilities are available through the API
 * @param result_columns if specified, a list a columns you want in the resultset
 * @return JSONObject
 */
public JSONObject getSearchResults(FotoliaSearchQuery query,ArrayList<String> result_columns){
  FotoliaApiArgs args;
  args=query.getFotoliaApiArgs();
  for (  String column : result_columns) {
    args.add(new BasicNameValuePair("result_columns[]",column));
  }
  return this._api("getSearchResults",args);
}
 

Example 18

From project accesointeligente, under directory /src/org/accesointeligente/server/robots/.

Source file: SIAC.java

  16 
vote

@Override public void login() throws Exception {
  if (characterEncoding == null) {
    detectCharacterEncoding();
  }
  List<NameValuePair> formParams;
  HttpPost post;
  HttpResponse response;
  TagNode document, hiddenUser;
  try {
    formParams=new ArrayList<NameValuePair>();
    formParams.add(new BasicNameValuePair("usuario",username));
    formParams.add(new BasicNameValuePair("clave",password));
    formParams.add(new BasicNameValuePair("accion","login"));
    post=new HttpPost(baseUrl + "/formulario.gov");
    post.addHeader("Referer",baseUrl + "/formulario.gov?accion=ingresa");
    post.setEntity(new UrlEncodedFormEntity(formParams,characterEncoding));
    response=client.execute(post);
    document=cleaner.clean(new InputStreamReader(response.getEntity().getContent(),characterEncoding));
    hiddenUser=document.findElementByAttValue("id","user",true,true);
    if (hiddenUser == null || !hiddenUser.hasAttribute("value") || hiddenUser.getAttributeByName("value").equals("0")) {
      throw new RobotException("Invalid user id field");
    }
    userId=hiddenUser.getAttributeByName("value");
    loggedIn=true;
  }
 catch (  Exception ex) {
    logger.error(ex.getMessage(),ex);
    throw ex;
  }
}
 

Example 19

From project android-api_1, under directory /android-lib/src/com/catchnotes/api/.

Source file: CatchAPI.java

  16 
vote

/** 
 * Deletes a note.
 * @param id ID of the note to be deleted
 * @param parentNodeId If you are deleting a comment, this is the parent note's ID.
 * @return RESULT_OK on success
 */
public int deleteNote(String id,String parentNodeId){
  int returnCode=RESULT_ERROR;
  HttpResponse response;
  if (parentNodeId == null || CatchNote.NODE_ID_NEVER_SYNCED.equals(parentNodeId)) {
    response=performDELETE(API_ENDPOINT_NOTES + '/' + id,null);
  }
 else {
    List<NameValuePair> params=new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("comment",id));
    response=performDELETE(API_ENDPOINT_COMMENT + '/' + parentNodeId,params);
  }
  if (response != null) {
    if (isResponseOK(response)) {
      returnCode=RESULT_OK;
    }
 else     if (isResponseUnauthorized(response)) {
      returnCode=RESULT_UNAUTHORIZED;
    }
 else     if (isResponseNotFound(response)) {
      returnCode=RESULT_NOT_FOUND;
    }
 else     if (isResponseServerError(response)) {
      returnCode=RESULT_SERVER_ERROR;
    }
 else {
      returnCode=RESULT_ERROR_PENDING;
    }
    consumeResponse(response);
  }
  return returnCode;
}
 

Example 20

From project Android-SyncAdapter-JSON-Server-Example, under directory /src/com/example/android/samplesync/client/.

Source file: NetworkUtilities.java

  16 
vote

/** 
 * Fetches the list of friend data updates from the server
 * @param account The account being synced.
 * @param authtoken The authtoken stored in AccountManager for this account
 * @param lastUpdated The last time that sync was performed
 * @return list The list of updates received from the server.
 */
public static List<User> fetchFriendUpdates(Account account,String authtoken,Date lastUpdated) throws JSONException, ParseException, IOException, AuthenticationException {
  final ArrayList<User> friendList=new ArrayList<User>();
  final ArrayList<NameValuePair> params=new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair(PARAM_USERNAME,account.name));
  params.add(new BasicNameValuePair(PARAM_PASSWORD,authtoken));
  if (lastUpdated != null) {
    final SimpleDateFormat formatter=new SimpleDateFormat("yyyy/MM/dd HH:mm");
    formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    params.add(new BasicNameValuePair(PARAM_UPDATED,formatter.format(lastUpdated)));
  }
  Log.i(TAG,params.toString());
  HttpEntity entity=null;
  entity=new UrlEncodedFormEntity(params);
  final HttpPost post=new HttpPost(FETCH_FRIEND_UPDATES_URI);
  post.addHeader(entity.getContentType());
  post.setEntity(entity);
  maybeCreateHttpClient();
  final HttpResponse resp=mHttpClient.execute(post);
  final String response=EntityUtils.toString(resp.getEntity());
  if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    final JSONArray friends=new JSONArray(response);
    Log.d(TAG,response);
    for (int i=0; i < friends.length(); i++) {
      friendList.add(User.valueOf(friends.getJSONObject(i)));
    }
  }
 else {
    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
      Log.e(TAG,"Authentication exception in fetching remote contacts");
      throw new AuthenticationException();
    }
 else {
      Log.e(TAG,"Server error in fetching remote contacts: " + resp.getStatusLine());
      throw new IOException();
    }
  }
  return friendList;
}
 

Example 21

From project androidtracks, under directory /src/org/sfcta/cycletracks/.

Source file: TripUploader.java

  16 
vote

private List<NameValuePair> getPostData(long tripId) throws JSONException {
  JSONObject coords=getCoordsJSON(tripId);
  JSONObject user=getUserJSON();
  String deviceId=getDeviceId();
  Vector<String> tripData=getTripData(tripId);
  String notes=tripData.get(0);
  String purpose=tripData.get(1);
  String startTime=tripData.get(2);
  String endTime=tripData.get(3);
  List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(2);
  nameValuePairs.add(new BasicNameValuePair("coords",coords.toString()));
  nameValuePairs.add(new BasicNameValuePair("user",user.toString()));
  nameValuePairs.add(new BasicNameValuePair("device",deviceId));
  nameValuePairs.add(new BasicNameValuePair("notes",notes));
  nameValuePairs.add(new BasicNameValuePair("purpose",purpose));
  nameValuePairs.add(new BasicNameValuePair("start",startTime));
  nameValuePairs.add(new BasicNameValuePair("end",endTime));
  nameValuePairs.add(new BasicNameValuePair("version","2"));
  return nameValuePairs;
}
 

Example 22

From project andstatus, under directory /src/org/andstatus/app/net/.

Source file: ConnectionBasicAuth.java

  16 
vote

@Override public JSONObject updateStatus(String message,String inReplyToId) throws ConnectionException {
  String url=getApiUrl(apiEnum.STATUSES_UPDATE);
  List<NameValuePair> formParams=new ArrayList<NameValuePair>();
  formParams.add(new BasicNameValuePair("status",message));
  if (!TextUtils.isEmpty(inReplyToId)) {
    formParams.add(new BasicNameValuePair("in_reply_to_status_id",inReplyToId));
  }
  JSONObject jObj=null;
  try {
    jObj=new JSONObject(postRequest(url,new UrlEncodedFormEntity(formParams,HTTP.UTF_8)));
    String error=jObj.optString("error");
    if ("Could not authenticate you.".equals(error)) {
      throw new ConnectionException(error);
    }
  }
 catch (  UnsupportedEncodingException e) {
    Log.e(TAG,e.toString());
  }
catch (  JSONException e) {
    throw new ConnectionException(e);
  }
  return jObj;
}
 

Example 23

From project andtweet, under directory /src/com/xorcode/andtweet/net/.

Source file: ConnectionBasicAuth.java

  16 
vote

@Override public JSONObject updateStatus(String message,long inReplyToId) throws ConnectionException {
  String url=STATUSES_UPDATE_URL;
  List<NameValuePair> formParams=new ArrayList<NameValuePair>();
  formParams.add(new BasicNameValuePair("status",message));
  if (inReplyToId > 0) {
    formParams.add(new BasicNameValuePair("in_reply_to_status_id",String.valueOf(inReplyToId)));
  }
  JSONObject jObj=null;
  try {
    jObj=new JSONObject(postRequest(url,new UrlEncodedFormEntity(formParams,HTTP.UTF_8)));
    String error=jObj.optString("error");
    if ("Could not authenticate you.".equals(error)) {
      throw new ConnectionException(error);
    }
  }
 catch (  UnsupportedEncodingException e) {
    Log.e(TAG,e.toString());
  }
catch (  JSONException e) {
    throw new ConnectionException(e);
  }
  return jObj;
}
 

Example 24

From project aranea, under directory /webapp/src/test/java/no/dusken/aranea/integration/test/.

Source file: AbstractIntegrationTest.java

  16 
vote

private void checkValidity(){
  try {
    HttpPost post=new HttpPost("http://validator.w3.org/check");
    List<NameValuePair> formparams=new ArrayList<NameValuePair>();
    String pageSource=webDriver.getPageSource();
    formparams.add(new BasicNameValuePair("fragment",pageSource));
    formparams.add(new BasicNameValuePair("output","json"));
    UrlEncodedFormEntity entity=new UrlEncodedFormEntity(formparams,"UTF-8");
    post.setEntity(entity);
    HttpResponse httpResponse=httpclient.execute(post);
    HttpEntity responseEntity=httpResponse.getEntity();
    Map values=mapper.readValue(responseEntity.getContent(),Map.class);
    checkValues((List<Map<String,Object>>)values.get("messages"));
  }
 catch (  IOException e) {
    fail("Error when checking validity: " + e.getMessage());
    e.printStackTrace();
  }
}
 

Example 25

From project azure4j-blog-samples, under directory /ACSManagementService/src/com/persistent/azure/acs/.

Source file: ACSAuthenticationHelper.java

  16 
vote

/** 
 * Get OAuth SWT token from ACS
 */
private String getTokenFromACS(String acsNamespace,String acsMgmtPassword){
  try {
    DefaultHttpClient httpClient=new DefaultHttpClient();
    HttpPost httpPost=new HttpPost(String.format(ACSAuthenticationHelper.AcsTokenServiceUrl,acsNamespace));
    List<NameValuePair> listNameValuePairs=new ArrayList<NameValuePair>();
    listNameValuePairs.add(new BasicNameValuePair("grant_type","client_credentials"));
    listNameValuePairs.add(new BasicNameValuePair("client_id",managementUserName));
    listNameValuePairs.add(new BasicNameValuePair("client_secret",acsMgmtPassword));
    listNameValuePairs.add(new BasicNameValuePair("scope",String.format(ACSAuthenticationHelper.AcsODataServiceUrl,acsNamespace)));
    UrlEncodedFormEntity formEntity=new UrlEncodedFormEntity(listNameValuePairs);
    httpPost.setEntity(formEntity);
    HttpResponse httpResponse=httpClient.execute(httpPost);
    HttpEntity entity=httpResponse.getEntity();
    InputStream inputStream=entity.getContent();
    InputStreamReader streamReader=new InputStreamReader(inputStream);
    BufferedReader bufferedReader=new BufferedReader(streamReader);
    String string=null;
    StringBuffer response=new StringBuffer();
    while ((string=bufferedReader.readLine()) != null) {
      response.append(string);
    }
    JSONObject obj=new JSONObject(response.toString());
    return obj.getString("access_token");
  }
 catch (  Exception e) {
    e.printStackTrace();
    return null;
  }
}
 

Example 26

From project b3log-latke, under directory /latke-client/src/main/java/org/b3log/latke/client/.

Source file: LatkeClient.java

  16 
vote

/** 
 * Gets repository names.
 * @return repository names
 * @throws Exception exception
 */
private static Set<String> getRepositoryNames() throws Exception {
  final HttpClient httpClient=new DefaultHttpClient();
  final List<NameValuePair> qparams=new ArrayList<NameValuePair>();
  qparams.add(new BasicNameValuePair("userName",userName));
  qparams.add(new BasicNameValuePair("password",password));
  final URI uri=URIUtils.createURI("http",serverAddress,-1,GET_REPOSITORY_NAMES,URLEncodedUtils.format(qparams,"UTF-8"),null);
  final HttpGet request=new HttpGet();
  request.setURI(uri);
  if (verbose) {
    System.out.println("Getting repository names[" + GET_REPOSITORY_NAMES + "]");
  }
  final HttpResponse httpResponse=httpClient.execute(request);
  final InputStream contentStream=httpResponse.getEntity().getContent();
  final String content=IOUtils.toString(contentStream).trim();
  if (verbose) {
    printResponse(content);
  }
  final JSONObject result=new JSONObject(content);
  final JSONArray repositoryNames=result.getJSONArray("repositoryNames");
  final Set<String> ret=new HashSet<String>();
  for (int i=0; i < repositoryNames.length(); i++) {
    final String repositoryName=repositoryNames.getString(i);
    ret.add(repositoryName);
    final File dir=new File(backupDir.getPath() + File.separatorChar + repositoryName);
    if (!dir.exists() && verbose) {
      dir.mkdir();
      System.out.println("Created a directory[name=" + dir.getName() + "] under backup directory[path="+ backupDir.getPath()+ "]");
    }
  }
  return ret;
}
 

Example 27

From project basiclti-portlet, under directory /src/main/java/au/edu/anu/portal/portlets/basiclti/support/.

Source file: HttpSupport.java

  16 
vote

/** 
 * Make a POST request with the given Map of parameters to be encoded
 * @param address	address to POST to
 * @param params	Map of params to use as the form parameters
 * @return
 */
public static String doPost(String address,Map<String,String> params){
  HttpClient httpclient=new DefaultHttpClient();
  try {
    HttpPost httppost=new HttpPost(address);
    List<NameValuePair> formparams=new ArrayList<NameValuePair>();
    for (    Map.Entry<String,String> entry : params.entrySet()) {
      formparams.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
    }
    UrlEncodedFormEntity entity=new UrlEncodedFormEntity(formparams,HTTP.UTF_8);
    httppost.setEntity(entity);
    HttpResponse response=httpclient.execute(httppost);
    String responseContent=EntityUtils.toString(response.getEntity());
    return responseContent;
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
 finally {
    httpclient.getConnectionManager().shutdown();
  }
  return null;
}
 

Example 28

From project bbb-java, under directory /src/main/java/org/mconf/web/.

Source file: Authentication.java

  16 
vote

/** 
 * Example of the use of cookies: http://www.java-tips.org/other-api-tips/httpclient/how-to-use-http-cookies.html
 * @param username
 * @param password
 * @return
 * @throws HttpException
 * @throws IOException
 */
private boolean authenticate(String username,String password) throws HttpException, IOException {
  List<NameValuePair> formparams=new ArrayList<NameValuePair>();
  formparams.add(new BasicNameValuePair("login",username));
  formparams.add(new BasicNameValuePair("password",password));
  UrlEncodedFormEntity entity=new UrlEncodedFormEntity(formparams,"UTF-8");
  HttpPost method=new HttpPost(server + "/session");
  method.setEntity(entity);
  HttpContext localContext=new BasicHttpContext();
  HttpResponse response=client.execute(method,localContext);
  if (response.getStatusLine().getStatusCode() != 302) {
    log.error("Invalid response code " + response.getStatusLine().getStatusCode());
    return false;
  }
  if (!response.containsHeader("Location") || !response.getFirstHeader("Location").getValue().equals(server + "/home")) {
    log.error("Invalid password");
    return false;
  }
  if (!response.containsHeader("Set-Cookie")) {
    log.error("The response doesn't have an authenticated cookie");
    return false;
  }
  cookie=response.getFirstHeader("Set-Cookie").getValue();
  log.info("Authenticated on " + server);
  return true;
}
 

Example 29

From project BF3-Battlelog, under directory /src/com/ninetwozero/battlelog/http/.

Source file: RequestHandler.java

  16 
vote

public String post(String link,PostData[] postDataArray,int extraHeaders) throws RequestHandlerException {
  if ("".equals(link)) {
    throw new RequestHandlerException("No link found.");
  }
  HttpPost httpPost=new HttpPost(link);
  if (extraHeaders > 0) {
    if (extraHeaders == 1) {
      httpPost.setHeaders(HttpHeaders.POST_HEADERS.get(extraHeaders));
    }
 else     if (extraHeaders == 2) {
      httpPost.setHeaders(HttpHeaders.POST_HEADERS.get(extraHeaders));
    }
 else     if (extraHeaders == 3) {
      httpPost.setHeaders(HttpHeaders.POST_HEADERS.get(extraHeaders));
    }
  }
  List<BasicNameValuePair> nameValuePairs=new ArrayList<BasicNameValuePair>();
  HttpEntity httpEntity;
  HttpResponse httpResponse;
  for (  PostData data : postDataArray) {
    nameValuePairs.add(new BasicNameValuePair(data.getField(),(data.isHash()) ? this.hash(data.getValue()) : data.getValue()));
  }
  try {
    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));
    httpResponse=httpClient.execute(httpPost);
    httpEntity=httpResponse.getEntity();
    if (httpEntity != null) {
      return EntityUtils.toString(httpEntity);
    }
  }
 catch (  UnknownHostException ex) {
    throw new RequestHandlerException("Host unreachable - please restart your 3G connection and try again.");
  }
catch (  Exception e) {
    e.printStackTrace();
  }
  return "";
}
 

Example 30

From project bookmarktodesktop-android-application, under directory /src/be/vbsteven/bmtodesk/.

Source file: BackgroundSharingService.java

  16 
vote

/** 
 * sends the bookmark to the server in a POST request
 * @param title
 * @param url
 */
private void sendToServer(final String title,final String url){
  showProgress();
  String username=Global.getUsername(BackgroundSharingService.this);
  String password=Global.getPassword(BackgroundSharingService.this);
  String responseMessage;
  try {
    HttpClient httpclient=new DefaultHttpClient();
    HttpPost post=new HttpPost(URI.create(URL));
    ArrayList<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(4);
    nameValuePairs.add(new BasicNameValuePair("username",username));
    nameValuePairs.add(new BasicNameValuePair("password",password));
    nameValuePairs.add(new BasicNameValuePair("title",title));
    nameValuePairs.add(new BasicNameValuePair("url",url));
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response=httpclient.execute(post);
    BufferedReader reader=new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"UTF-8"));
    responseMessage=reader.readLine();
  }
 catch (  Exception e) {
    responseMessage="REQUESTFAILED";
  }
  hideProgress();
  onResult(responseMessage);
}
 

Example 31

From project BusFollower, under directory /src/net/argilo/busfollower/ocdata/.

Source file: OCTranspoDataFetcher.java

  16 
vote

public GetNextTripsForStopResult getNextTripsForStop(String stopNumber,String routeNumber) throws IOException, XmlPullParserException, IllegalArgumentException {
  validateStopNumber(stopNumber);
  validateRouteNumber(routeNumber);
  httpClient=new DefaultHttpClient(getHttpParams());
  HttpPost post=new HttpPost("https://api.octranspo1.com/v1.1/GetNextTripsForStop");
  List<NameValuePair> params=new ArrayList<NameValuePair>(4);
  params.add(new BasicNameValuePair("appID",context.getString(R.string.oc_transpo_application_id)));
  params.add(new BasicNameValuePair("apiKey",context.getString(R.string.oc_transpo_application_key)));
  params.add(new BasicNameValuePair("routeNo",routeNumber));
  params.add(new BasicNameValuePair("stopNo",stopNumber));
  post.setEntity(new UrlEncodedFormEntity(params));
  HttpResponse response=httpClient.execute(post);
  XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
  factory.setNamespaceAware(true);
  XmlPullParser xpp=factory.newPullParser();
  InputStream in=response.getEntity().getContent();
  xpp.setInput(in,"UTF-8");
  xpp.next();
  xpp.next();
  xpp.next();
  xpp.next();
  GetNextTripsForStopResult result=new GetNextTripsForStopResult(context,db,xpp,stopNumber);
  in.close();
  return result;
}
 

Example 32

From project c2dm4j, under directory /src/main/java/org/whispercomm/c2dm4j/impl/.

Source file: C2dmHttpResponseHandler.java

  16 
vote

private NameValuePair parseBody(HttpResponse response) throws UnexpectedResponseException {
  try {
    String body=EntityUtils.toString(response.getEntity());
    String[] splitBody=SPLITTER.split(body);
    if (splitBody.length == 2) {
      return new BasicNameValuePair(splitBody[0],splitBody[1]);
    }
 else {
      throw new UnexpectedResponseException(String.format("Unexpected format of message body:\n%s",body));
    }
  }
 catch (  ParseException e) {
    throw new UnexpectedResponseException(e);
  }
catch (  IOException e) {
    throw new UnexpectedResponseException(e);
  }
}
 

Example 33

From project CityBikes, under directory /src/net/homelinux/penecoptero/android/citybikes/app/.

Source file: RESTHelper.java

  16 
vote

public String restPOST(String url,Map<String,String> kvPairs) throws ClientProtocolException, IOException, HttpException {
  DefaultHttpClient httpclient=new DefaultHttpClient();
  if (this.authenticated)   httpclient=this.setCredentials(httpclient,url);
  HttpPost httpmethod=new HttpPost(url);
  if (kvPairs != null && kvPairs.isEmpty() == false) {
    List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(kvPairs.size());
    String k, v;
    Iterator<String> itKeys=kvPairs.keySet().iterator();
    while (itKeys.hasNext()) {
      k=itKeys.next();
      v=kvPairs.get(k);
      nameValuePairs.add(new BasicNameValuePair(k,v));
    }
    httpmethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));
  }
  HttpResponse response;
  String result=null;
  try {
    response=httpclient.execute(httpmethod);
    HttpEntity entity=response.getEntity();
    if (entity != null) {
      InputStream instream=entity.getContent();
      result=convertStreamToString(instream);
      instream.close();
    }
  }
 catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
  return result;
}
 

Example 34

From project DeskSMS, under directory /DeskSMS/src/com/koushikdutta/desktopsms/.

Source file: TickleServiceHelper.java

  16 
vote

static void registerWithServer(final Context context,boolean sendEmail) throws Exception {
  String ascidCookie=getCookie(context);
  Settings settings=Settings.getInstance(context);
  final String registration=settings.getString("registration_id");
  DefaultHttpClient client=new DefaultHttpClient();
  URI uri=new URI(ServiceHelper.REGISTER_URL);
  HttpPost post=new HttpPost(uri);
  ArrayList<NameValuePair> params=new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("device_id",Helper.getSafeDeviceId(context)));
  params.add(new BasicNameValuePair("registration_id",registration));
  params.add(new BasicNameValuePair("version_code",String.valueOf(DesktopSMSApplication.mVersionCode)));
  params.add(new BasicNameValuePair("send_email",String.valueOf(sendEmail)));
  UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"UTF-8");
  post.setEntity(entity);
  post.setHeader("X-Same-Domain","1");
  post.setHeader("Cookie",ascidCookie);
  HttpResponse res=client.execute(post);
  Log.i(LOGTAG,"Status code from register: " + res.getStatusLine().getStatusCode());
  if (res.getStatusLine().getStatusCode() != 200)   throw new Exception("status from server: " + res.getStatusLine().getStatusCode());
}
 

Example 35

From project DigitbooksExamples, under directory /DigitbooksExamples/src/fr/digitbooks/android/examples/chapitre08/.

Source file: RateDigitbooksActivity.java

  16 
vote

@Override protected String doInBackground(String... params){
  rating=Float.parseFloat(params[1]);
  comment=params[0];
  String result=null;
  StringBuffer stringBuffer=new StringBuffer("");
  BufferedReader bufferedReader=null;
  try {
    HttpPost httpPost=new HttpPost(Config.URL_SERVER + "add");
    List<NameValuePair> parameters=new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("comment",params[0]));
    parameters.add(new BasicNameValuePair("rating",params[1]));
    UrlEncodedFormEntity formEntity=new UrlEncodedFormEntity(parameters,HTTP.UTF_8);
    httpPost.setEntity(formEntity);
    AndroidHttpClient httpClient=AndroidHttpClient.newInstance("");
    HttpResponse httpResponse=httpClient.execute(httpPost);
    InputStream inputStream=httpResponse.getEntity().getContent();
    bufferedReader=new BufferedReader(new InputStreamReader(inputStream),1024);
    String readLine=bufferedReader.readLine();
    while (readLine != null) {
      stringBuffer.append(readLine);
      readLine=bufferedReader.readLine();
    }
    httpClient.close();
  }
 catch (  Exception e) {
    return null;
  }
 finally {
    if (bufferedReader != null) {
      try {
        bufferedReader.close();
      }
 catch (      IOException e) {
        return null;
      }
    }
    result=stringBuffer.toString();
  }
  return result;
}
 

Example 36

From project EasySOA, under directory /easysoa-proxy/easysoa-proxy-core/easysoa-proxy-core-httpdiscoveryproxy-test/src/test/java/org/easysoa/test/messaging/.

Source file: TemplateTest.java

  16 
vote

/** 
 * Deprecated : This test worked with the first templating solution. This solution is no more used today.  Technical test - Get the form generated from an exchange record - Check that the form contains required fields - Send a simulated post request with custom form values ReplayTemplateWithDefaultValue : Use the replayTemplate.html velocity HTML template to build a form. Only with REST Exchanges
 * @throws ClientProtocolException
 * @throws IOException
 */
@Test @Ignore @Deprecated public void replayTemplateWithDefaultValue() throws ClientProtocolException, IOException {
  String testRunName="Twitter_Rest_Test_Run";
  DefaultHttpClient httpClient=new DefaultHttpClient();
  HttpGet getRequest=new HttpGet("http://localhost:8090/runManager/exchangeRecordStore/replayTemplate.html");
  String response=httpClient.execute(getRequest,new BasicResponseHandler());
  logger.debug("GetTemplate response = " + response);
  assertTrue(response.contains("comment (String) : <input type=\"text\" name=\"comment\" value=\"test\" />"));
  HttpPost postRequest=new HttpPost("http://localhost:" + EasySOAConstants.EXCHANGE_RECORD_REPLAY_SERVICE_PORT + "/templates/replayWithTemplate/"+ testRunName+ "/1/testTemplate");
  List<NameValuePair> formparams=new ArrayList<NameValuePair>();
  formparams.add(new BasicNameValuePair("user","FR3Bourgogne.xml"));
  formparams.add(new BasicNameValuePair("param2","value2"));
  UrlEncodedFormEntity entity=new UrlEncodedFormEntity(formparams,"UTF-8");
  postRequest.setEntity(entity);
  response=httpClient.execute(postRequest,new BasicResponseHandler());
  logger.debug("replayWithTemplate response = " + response);
}
 

Example 37

From project eve-api, under directory /cdi/src/main/java/org/onsteroids/eve/api/connector/http/.

Source file: PooledHttpApiConnection.java

  16 
vote

@Override public XmlApiResult call(final String xmlPath,final ApiKey key,final Map<String,String> parameters) throws ApiException {
  if (httpClient == null) {
    initializeHttpClient();
  }
  Preconditions.checkNotNull(xmlPath,"XmlPath");
  LOG.debug("Requesting {}...",xmlPath);
  try {
    List<NameValuePair> qparams=Lists.newArrayList();
    if (key != null) {
      LOG.trace("Using ApiKey {}",key);
      qparams.add(new BasicNameValuePair("userID",Long.toString(key.getUserId())));
      qparams.add(new BasicNameValuePair("apiKey",key.getApiKey()));
    }
    if (parameters != null) {
      LOG.trace("Using parameters: {}",parameters);
      for (      Map.Entry<String,String> entry : parameters.entrySet()) {
        qparams.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
      }
    }
    final URI requestURI=URIUtils.createURI(serverUri.getScheme(),serverUri.getHost(),serverUri.getPort(),xmlPath,URLEncodedUtils.format(qparams,"UTF-8"),null);
    LOG.trace("Resulting URI: {}",requestURI);
    final HttpPost postRequest=new HttpPost(requestURI);
    LOG.trace("Fetching result from {}...",serverUri);
    final HttpResponse response=httpClient.execute(postRequest);
    final InputStream stream=response.getEntity().getContent();
    final DocumentBuilder builder=builderFactory.newDocumentBuilder();
    final Document doc=builder.parse(stream);
    return apiCoreParser.call(doc,xmlPath,key,parameters,serverUri);
  }
 catch (  ApiException e) {
    throw e;
  }
catch (  Exception e) {
    throw new InternalApiException(e);
  }
}
 

Example 38

From project FlipDroid, under directory /app/src/com/goal98/flipdroid2/model/google/.

Source file: GReader.java

  16 
vote

private void setAuth_params(){
  auth_params="accountType=HOSTED_OR_GOOGLE&Email=" + this.email + "&Passwd="+ this.password+ "&service=reader&source=SRZ-gr";
  this.params=new BasicHttpParams();
  this.params.setParameter("accountType","HOSTED_OR_GOOGLE");
  this.params.setParameter("Email",this.email);
  this.params.setParameter("Passwd",this.password);
  this.params.setParameter("service","reader");
  this.params.setParameter("source","SRZ-gr");
  this.paramsNameValuePairs=new ArrayList<NameValuePair>();
  paramsNameValuePairs.add(new BasicNameValuePair("accountType","HOSTED_OR_GOOGLE"));
  paramsNameValuePairs.add(new BasicNameValuePair("Email",this.email));
  paramsNameValuePairs.add(new BasicNameValuePair("Passwd",this.password));
  paramsNameValuePairs.add(new BasicNameValuePair("service","reader"));
  paramsNameValuePairs.add(new BasicNameValuePair("source","SRZ-gr"));
}
 

Example 39

From project Funf-Ohmage, under directory /src/org/ohmage/.

Source file: OhmageApi.java

  16 
vote

public AuthenticateResponse authenticate(String serverUrl,String username,String password,String client){
  final boolean GZIP=false;
  String url=serverUrl + AUTHENTICATE_PATH;
  try {
    List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("user",username));
    nameValuePairs.add(new BasicNameValuePair("password",password));
    nameValuePairs.add(new BasicNameValuePair("client",client));
    UrlEncodedFormEntity formEntity=new UrlEncodedFormEntity(nameValuePairs);
    return parseAuthenticateResponse(doHttpPost(url,formEntity,GZIP));
  }
 catch (  IOException e) {
    Log.e(TAG,"IOException while creating http entity",e);
    return new AuthenticateResponse(Result.INTERNAL_ERROR,null,null,null);
  }
}
 

Example 40

From project Gaggle, under directory /src/com/geeksville/location/.

Source file: LeonardoUpload.java

  16 
vote

/** 
 * Upload a flight to Leonardo
 * @param username
 * @param password
 * @param postURL
 * @param shortFilename
 * @param igcFile we will take care of closing this stram
 * @return null for success, otherwise a string description of the problem
 * @throws IOException
 */
public static String upload(String username,String password,String postURL,int competitionClass,String shortFilename,String igcFile,int connectionTimeout,int operationTimeout) throws IOException {
  int i=shortFilename.lastIndexOf('.');
  if (i >= 1)   shortFilename=shortFilename.substring(0,i);
  String sCompetitionClass=String.valueOf(competitionClass);
  HttpParams httpParameters=new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(httpParameters,connectionTimeout);
  HttpConnectionParams.setSoTimeout(httpParameters,operationTimeout);
  HttpClient httpclient=new DefaultHttpClient(httpParameters);
  httpclient.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,false);
  HttpPost httppost=new HttpPost(postURL);
  List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>();
  nameValuePairs.add(new BasicNameValuePair("user",username));
  nameValuePairs.add(new BasicNameValuePair("pass",password));
  nameValuePairs.add(new BasicNameValuePair("igcfn",shortFilename));
  nameValuePairs.add(new BasicNameValuePair("Klasse",sCompetitionClass));
  nameValuePairs.add(new BasicNameValuePair("IGCigcIGC",igcFile));
  httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
  HttpResponse response=httpclient.execute(httppost);
  HttpEntity entity=response.getEntity();
  String resp=EntityUtils.toString(entity);
  if (resp.contains("flight scored"))   resp=null;
 else {
    int bodLoc=resp.indexOf("<body>");
    if (bodLoc >= 0)     resp=resp.substring(bodLoc + 6);
    int probLoc=resp.indexOf("problem");
    if (probLoc >= 0)     resp=resp.substring(probLoc + 7);
    if (resp.startsWith("<br>"))     resp=resp.substring(4);
    int markLoc=resp.indexOf('<');
    if (markLoc >= 0)     resp=resp.substring(0,markLoc);
    resp=resp.trim();
  }
  return resp;
}
 

Example 41

From project generic-store-for-android, under directory /src/com/wareninja/opensource/common/.

Source file: CustomBugSenseReportSender.java

  16 
vote

private void submitError(String hash,String data){
  DefaultHttpClient httpClient=new DefaultHttpClient();
  HttpParams params=httpClient.getParams();
  HttpProtocolParams.setUseExpectContinue(params,false);
  HttpConnectionParams.setConnectionTimeout(params,TIMEOUT);
  HttpConnectionParams.setSoTimeout(params,TIMEOUT);
  HttpPost httpPost=new HttpPost(bugSenseEndPoint);
  httpPost.addHeader("X-BugSense-Api-Key",bugSenseApiKey);
  List<NameValuePair> nvps=new ArrayList<NameValuePair>();
  nvps.add(new BasicNameValuePair("data",data));
  nvps.add(new BasicNameValuePair("hash",hash));
  try {
    httpPost.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8));
    HttpResponse response=httpClient.execute(httpPost);
    HttpEntity entity=response.getEntity();
    Log.d(TAG,"entity : " + entity);
  }
 catch (  Exception ex) {
    Log.e(TAG,"Error sending exception stacktrace",ex);
  }
}
 

Example 42

From project Couch-RQS, under directory /src/com/couchrqs/.

Source file: Queue.java

  15 
vote

/** 
 * Get as many as maxNumberOfMessages messages from the specified view.<br /> The descending param is used to get LIFO (if true) or FIFO (if false) behavior.
 */
private List<Document> getPendingDocsFromView(String viewName,final int maxNumberOfMessages,final boolean descending) throws RQSException {
  List<NameValuePair> params=new ArrayList<NameValuePair>(){
{
      add(new BasicNameValuePair("include_docs","true"));
      add(new BasicNameValuePair("limit",String.valueOf(maxNumberOfMessages)));
      if (descending)       add(new BasicNameValuePair("descending","true"));
    }
  }
;
  try {
    return db.queryView(RQS_DESIGN_DOC_NAME,viewName,params);
  }
 catch (  Exception e) {
    throw new RQSException(e);
  }
}