Java Code Examples for org.apache.http.NameValuePair

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 httpbuilder, under directory /src/main/java/groovyx/net/http/.

Source file: ParserRegistry.java

  22 
vote

/** 
 * Helper method to get the charset from the response.  This should be done  when manually parsing any text response to ensure it is decoded using the correct charset. For instance:<pre> Reader reader = new InputStreamReader( resp.getEntity().getContent(),  ParserRegistry.getCharset( resp ) );</pre>
 * @param resp
 */
public static String getCharset(HttpResponse resp){
  try {
    NameValuePair charset=resp.getEntity().getContentType().getElements()[0].getParameterByName("charset");
    if (charset == null || charset.getValue().trim().equals("")) {
      log.debug("Could not find charset in response; using " + defaultCharset);
      return defaultCharset;
    }
    return charset.getValue();
  }
 catch (  RuntimeException ex) {
    log.warn("Could not parse charset from content-type header in response");
    return Charset.defaultCharset().name();
  }
}
 

Example 2

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

Source file: C2dmHttpResponseHandler.java

  17 
vote

@Override public Response handleResponse(HttpResponse response) throws IOException {
  AuthToken token=getAuthToken(response);
switch (response.getStatusLine().getStatusCode()) {
case 200:
    NameValuePair body=parseBody(response);
  ResponseType type=getResponseType(body);
switch (type) {
case Success:
  return new SuccessResponseImpl(body.getValue(),message,token);
default :
return new ResponseImpl(type,message,token);
}
case 503:
Date retryAfter=getRetryAfter(response);
return new UnavailableResponseImpl(retryAfter,message,token);
case 401:
return new ResponseImpl(ResponseType.Unauthorized,message,token);
default :
throw new UnexpectedResponseException(String.format("Unexpected HTTP status code: %d",response.getStatusLine().getStatusCode()));
}
}
 

Example 3

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

Source file: TickleServiceHelper.java

  17 
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 4

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

Source file: JSONParser.java

  16 
vote

public JSONObject getJSONFromUrl(String url,List<NameValuePair> params){
  try {
    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();
  }
 catch (  UnsupportedEncodingException e) {
    e.printStackTrace();
  }
catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException 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();
    json=sb.toString();
    Log.e("JSON",json);
  }
 catch (  Exception e) {
    Log.e("Buffer Error","Error converting result " + e.toString());
  }
  try {
    jObj=new JSONObject(json);
  }
 catch (  JSONException e) {
    Log.e("JSON Parser","Error parsing data " + e.toString());
  }
  return jObj;
}
 

Example 5

From project 2Degrees-Toolbox, under directory /Toolbox/src/biz/shadowservices/DegreesToolbox/.

Source file: HttpPoster.java

  15 
vote

public HttpPoster(URI uri,List<? extends NameValuePair> values){
  httppost=new HttpPost(uri);
  try {
    httppost.setEntity(new UrlEncodedFormEntity(values,HTTP.UTF_8));
  }
 catch (  UnsupportedEncodingException e) {
    Log.e(TAG,"Error: Unsupported encoding exception on " + httppost.getURI());
  }
}
 

Example 6

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

Source file: SIAC.java

  15 
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 7

From project Amantech, under directory /Android/cloudLogin/src/com/cloude/entropin/.

Source file: GAEConnector.java

  15 
vote

/** 
 */
public int POSTContent(String relativeUrl,List<NameValuePair> params,boolean authenticated,boolean disableRedirect) throws Exception {
  DefaultHttpClient httpClient=this.CreateHttpClient(disableRedirect);
  HttpPost httpPost=new HttpPost(_gaeAppBaseUrl + relativeUrl);
  if (params != null) {
    UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"UTF-8");
    httpPost.setEntity(entity);
  }
  this.SetHttpRequestAuthCookie(httpPost,authenticated);
  HttpResponse httpResp=httpClient.execute(httpPost);
  _lastHttpCode=httpResp.getStatusLine().getStatusCode();
  Log.v("GetContent","httpStatusCode: " + _lastHttpCode);
  _lastContent=this.ReadTextFromHttpResponse(httpResp);
  Log.v("GetContent","content=" + _lastContent);
  return _lastHttpCode;
}
 

Example 8

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

Source file: CatchAPI.java

  15 
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 9

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

Source file: Bank.java

  15 
vote

public LoginPackage(Urllib urllib,List<NameValuePair> postData,String response,String loginTarget){
  this.urllib=urllib;
  this.postData=postData;
  this.response=response;
  this.loginTarget=loginTarget;
}
 

Example 10

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

Source file: NetworkUtilities.java

  15 
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 11

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

Source file: AjaxLoadingActivity.java

  15 
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 12

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

Source file: TripUploader.java

  15 
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 13

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

Source file: PostReporter.java

  15 
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 14

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

Source file: ConnectionBasicAuth.java

  15 
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 15

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

Source file: ConnectionBasicAuth.java

  15 
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 16

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

Source file: FileApiClientAdapterImpl.java

  15 
vote

private String buildFileListParams(FileListSearchParams fileListSearchParams){
  List<BasicNameValuePair> nameValuePairs=new ArrayList<BasicNameValuePair>();
  nameValuePairs.add(new BasicNameValuePair(LOCALE,fileListSearchParams.getLocale()));
  nameValuePairs.add(new BasicNameValuePair(URI_MASK,fileListSearchParams.getUriMask()));
  nameValuePairs.add(new BasicNameValuePair(LAST_UPLOADED_AFTER,DateFormatter.formatDate(fileListSearchParams.getLastUploadedAfter())));
  nameValuePairs.add(new BasicNameValuePair(LAST_UPLOADED_BEFORE,DateFormatter.formatDate(fileListSearchParams.getLastUploadedBefore())));
  nameValuePairs.add(new BasicNameValuePair(OFFSET,null == fileListSearchParams.getOffset() ? null : String.valueOf(fileListSearchParams.getOffset())));
  nameValuePairs.add(new BasicNameValuePair(LIMIT,null == fileListSearchParams.getLimit() ? null : String.valueOf(fileListSearchParams.getLimit())));
  nameValuePairs.addAll(getNameValuePairs(FILE_TYPES,fileListSearchParams.getFileTypes()));
  nameValuePairs.addAll(getNameValuePairs(CONDITIONS,fileListSearchParams.getConditions()));
  nameValuePairs.addAll(getNameValuePairs(ORDERBY,fileListSearchParams.getOrderBy()));
  return buildParamsQuery(nameValuePairs.toArray(new NameValuePair[nameValuePairs.size()]));
}
 

Example 17

From project appdriver, under directory /android/src/com/google/android/testing/nativedriver/server/.

Source file: AndroidNativeDriver.java

  15 
vote

/** 
 * Takes a string that looks like a URL and performs an operation based on the contents of the URL. Currently only starting activities is supported. <p> Supported URL type follows: <ul> <li> {@code and-activity://<Activity class name>}<br> start specified activity </ul>
 */
@Override public void get(String url){
  URI dest;
  try {
    dest=new URI(url);
  }
 catch (  URISyntaxException exception) {
    throw new IllegalArgumentException(exception);
  }
  if (!"and-activity".equals(dest.getScheme())) {
    throw new WebDriverException("Unrecognized scheme in URI: " + dest.toString());
  }
 else   if (!Strings.isNullOrEmpty(dest.getPath())) {
    throw new WebDriverException("Unrecognized path in URI: " + dest.toString());
  }
  Class<?> clazz;
  try {
    clazz=Class.forName(dest.getAuthority());
  }
 catch (  ClassNotFoundException exception) {
    throw new WebDriverException("The specified Activity class does not exist: " + dest.getAuthority(),exception);
  }
  for (  NameValuePair nvp : URLEncodedUtils.parse(dest,"utf8")) {
    if ("id".equals(nvp.getName())) {
      throw new WebDriverException("Moving to the specified activity is not supported.");
    }
  }
  startActivity(clazz);
}
 

Example 18

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

Source file: AbstractIntegrationTest.java

  15 
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 19

From project atlas, under directory /src/test/java/com/ning/atlas/.

Source file: TestJavaURI.java

  15 
vote

@Test public void testParams() throws Exception {
  URI uri=URI.create("cruft://waffles/hello?name=Happy");
  List<NameValuePair> pairs=URLEncodedUtils.parse(uri,"UTF-8");
  assertThat(pairs.size(),equalTo(1));
  for (  NameValuePair pair : pairs) {
    assertThat(pair.getName(),equalTo("name"));
    assertThat(pair.getValue(),equalTo("Happy"));
  }
}
 

Example 20

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

Source file: AudioBox.java

  15 
vote

/** 
 * Creates a HttpRequestBase
 * @param httpVerb the HTTP method to use for the request (ie: GET, PUT, POST and DELETE)
 * @param source usually reffers the Model that invokes method
 * @param dest Model that intercepts the response
 * @param action the remote action to execute on the model that executes the action (ex. "scrobble")
 * @param entity HttpEntity used by POST and PUT method
 * @return the HttpRequestBase 
 */
public HttpRequestBase createConnectionMethod(String httpVerb,String path,String action,ContentFormat format,List<NameValuePair> params){
  if (httpVerb == null) {
    httpVerb=IConnectionMethod.METHOD_GET;
  }
  String url=this.buildRequestUrl(path,action,httpVerb,format,params);
  HttpRequestBase method=null;
  if (IConnectionMethod.METHOD_POST.equals(httpVerb)) {
    log.debug("Building HttpMethod POST");
    method=new HttpPost(url);
  }
 else   if (IConnectionMethod.METHOD_PUT.equals(httpVerb)) {
    log.debug("Building HttpMethod PUT");
    method=new HttpPut(url);
  }
 else   if (IConnectionMethod.METHOD_DELETE.equals(httpVerb)) {
    log.debug("Building HttpMethod DELETE");
    method=new HttpDelete(url);
  }
 else {
    log.debug("Building HttpMethod GET");
    method=new HttpGet(url);
  }
  log.info("[ " + httpVerb + " ] "+ url);
  if (log.isDebugEnabled()) {
    log.debug("Setting default headers");
    log.debug("-> Accept-Encoding: gzip");
    log.debug("-> User-Agent: " + getConfiguration().getUserAgent());
  }
  method.addHeader("Accept-Encoding","gzip");
  method.addHeader("User-Agent",getConfiguration().getUserAgent());
  if (user != null && user.getAuthToken() != null) {
    method.addHeader(IConnector.X_AUTH_TOKEN_HEADER,user.getAuthToken());
    if (log.isDebugEnabled()) {
      log.debug("-> " + IConnector.X_AUTH_TOKEN_HEADER + ": ******"+ user.getAuthToken().substring(user.getAuthToken().length() - 5));
    }
  }
  return method;
}
 

Example 21

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

Source file: ACSAuthenticationHelper.java

  15 
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 22

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

Source file: LatkeClient.java

  15 
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 23

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

Source file: HttpSupport.java

  15 
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 24

From project BazaarUtils, under directory /src/com/android/vending/licensing/.

Source file: ServerManagedPolicy.java

  15 
vote

private Map<String,String> decodeExtras(String extras){
  Map<String,String> results=new HashMap<String,String>();
  try {
    URI rawExtras=new URI("?" + extras);
    List<NameValuePair> extraList=URLEncodedUtils.parse(rawExtras,"UTF-8");
    for (    NameValuePair item : extraList) {
      results.put(item.getName(),item.getValue());
    }
  }
 catch (  URISyntaxException e) {
    Log.w(TAG,"Invalid syntax error while decoding extras data from server.");
  }
  return results;
}
 

Example 25

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

Source file: Authentication.java

  15 
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 26

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

Source file: OwnedBookCreateHandler.java

  15 
vote

public void create(String isbn,ArrayList<String> shelves) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, IOException, NotAuthorizedException, NetworkException, BookNotFoundException {
  IsbnToId isbnToId=new IsbnToId(mManager);
  long id;
  try {
    id=isbnToId.isbnToId(isbn);
  }
 catch (  com.eleybourn.bookcatalogue.goodreads.GoodreadsManager.Exceptions.BookNotFoundException e) {
    throw new InvalidIsbnException();
  }
  HttpPost post=new HttpPost("http://www.goodreads.com/owned_books.xml");
  List<NameValuePair> parameters=new ArrayList<NameValuePair>();
  parameters.add(new BasicNameValuePair("owned_book[book_id]",Long.toString(id)));
  post.setEntity(new UrlEncodedFormEntity(parameters));
  OwnedBookCreateParser handler=new OwnedBookCreateParser();
  mManager.execute(post,handler,true);
  ShelfAddBookHandler shelfAdd=new ShelfAddBookHandler(mManager);
  for (  String shelf : shelves) {
    shelfAdd.add(shelf,handler.getBookId());
  }
}
 

Example 27

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

Source file: BackgroundSharingService.java

  15 
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 28

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

Source file: OCTranspoDataFetcher.java

  15 
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 29

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

Source file: RESTHelper.java

  15 
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 30

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);
  }
}
 

Example 31

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

Source file: Session.java

  15 
vote

protected String buildUrl(String url,NameValuePair[] params){
  url=((secure) ? "https" : "http") + "://" + host+ ":"+ port+ "/"+ url;
  if (params.length > 0) {
    url+="?";
  }
  for (  NameValuePair param : params) {
    url+=param.getName() + "=" + param.getValue();
  }
  return url;
}
 

Example 32

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

Source file: RateDigitbooksActivity.java

  15 
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 33

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

Source file: Engine.java

  15 
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 34

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

Source file: AbstractHttpFragment.java

  15 
vote

@Override protected Boolean doInBackground(ArrayList<NameValuePair>... params){
  if (isCancelled())   return false;
  publishProgress();
  String xml=mHandler.get(mShc,params[0]);
  if (xml != null) {
    ExtendedHashMap result=mHandler.parseSimpleResult(xml);
    String stateText=result.getString("statetext");
    if (stateText != null) {
      mResult=result;
      return true;
    }
  }
  return false;
}
 

Example 35

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

Source file: CaptureActivity.java

  15 
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 36

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

Source file: EzHttpRequest.java

  15 
vote

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

Example 37

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

  15 
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 38

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

Source file: PooledHttpApiConnection.java

  15 
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 39

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

Source file: GReader.java

  15 
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 40

From project friendica-for-android, under directory /mw-android-friendica-01/src/de/wikilab/android/friendica01/.

Source file: TwAjax.java

  15 
vote

private void runFileUpload() throws IOException {
  String lineEnd="\r\n";
  String twoHyphens="--";
  String boundary="d1934afa-f2e4-449b-99be-8be6ebfec594";
  Log.i("Andfrnd/TwAjax","URL=" + getURL());
  URL url=new URL(getURL());
  HttpURLConnection connection=(HttpURLConnection)url.openConnection();
  connection.setDoInput(true);
  connection.setDoOutput(true);
  connection.setUseCaches(false);
  connection.setRequestMethod("POST");
  if (this.myHttpAuthUser != null) {
    connection.setRequestProperty("Authorization","Basic " + Base64.encodeToString((this.myHttpAuthUser + ":" + this.myHttpAuthPass).getBytes(),Base64.NO_WRAP));
  }
  connection.setRequestProperty("Host",url.getHost());
  connection.setRequestProperty("Connection","Keep-Alive");
  connection.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
  DataOutputStream outputStream=new DataOutputStream(connection.getOutputStream());
  for (  NameValuePair nvp : myPostData) {
    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
    outputStream.writeBytes("Content-Disposition: form-data; name=\"" + nvp.getName() + "\""+ lineEnd);
    outputStream.writeBytes(lineEnd + nvp.getValue() + lineEnd);
  }
  for (  PostFile pf : myPostFiles) {
    pf.writeToStream(outputStream,boundary);
  }
  outputStream.writeBytes(twoHyphens + boundary + twoHyphens+ lineEnd);
  myHttpStatus=connection.getResponseCode();
  outputStream.flush();
  outputStream.close();
  if (myHttpStatus < 400) {
    myResult=convertStreamToString(connection.getInputStream());
  }
 else {
    myResult=convertStreamToString(connection.getErrorStream());
  }
  success=true;
}
 

Example 41

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

Source file: OhmageApi.java

  15 
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 42

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

Source file: LeonardoUpload.java

  15 
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 43

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

Source file: CustomBugSenseReportSender.java

  15 
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 44

From project gmarks-android, under directory /src/main/java/org/thomnichols/android/gmarks/.

Source file: BookmarksQueryService.java

  15 
vote

public void delete(String googleId) throws AuthException, NotFoundException, IOException {
  Uri requestURI=Uri.parse("https://www.google.com/bookmarks/api/thread").buildUpon().appendQueryParameter("xt",getXtParam()).appendQueryParameter("op","DeleteItems").build();
  JSONObject requestObj=new JSONObject();
  try {
    requestObj.put("deleteAllBookmarks",false);
    requestObj.put("deleteAllThreads",false);
    requestObj.put("urls",new JSONArray());
    JSONArray elementIDs=new JSONArray();
    elementIDs.put(googleId);
    requestObj.put("ids",elementIDs);
  }
 catch (  JSONException ex) {
    throw new IOException("JSON error while creating request");
  }
  String postString="{\"deleteAllBookmarks\":false,\"deleteAllThreads\":false,\"urls\":[],\"ids\":[\"" + googleId + "\"]}";
  List<NameValuePair> params=new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("td",postString));
  Log.v(TAG,"DELETE: " + requestURI);
  Log.v(TAG,"DELETE: " + postString);
  HttpPost post=new HttpPost(requestURI.toString());
  post.setEntity(new UrlEncodedFormEntity(params));
  HttpResponse resp=http.execute(post,this.ctx);
  int respCode=resp.getStatusLine().getStatusCode();
  if (respCode == 401)   throw new AuthException();
  if (respCode > 299)   throw new IOException("Unexpected response code: " + respCode);
  try {
    JSONObject respObj=parseJSON(resp);
    int deletedCount=respObj.getInt("numDeletedBookmarks");
    if (deletedCount < 1)     throw new NotFoundException("Bookmark could not be found; " + googleId);
    if (deletedCount > 1)     throw new IOException("Expected 1 deleted bookmark but got " + deletedCount);
  }
 catch (  JSONException ex) {
    throw new IOException("Response parse error",ex);
  }
}
 

Example 45

From project GraduationProject, under directory /G-Card/src/Hello/Tab/Widget/.

Source file: AppEngineClient.java

  15 
vote

public HttpResponse makeRequest(String urlPath,List<NameValuePair> params) throws Exception {
  HttpResponse res=makeRequestNoRetry(urlPath,params,false);
  if (res.getStatusLine().getStatusCode() == 500) {
    res=makeRequestNoRetry(urlPath,params,true);
  }
  return res;
}
 

Example 46

From project graylog2-server, under directory /src/main/java/org/graylog2/systeminformation/.

Source file: Sender.java

  15 
vote

public static void send(Map<String,Object> info,Core server){
  HttpClient httpClient=new DefaultHttpClient();
  try {
    HttpPost request=new HttpPost(getTarget(server));
    List<NameValuePair> nameValuePairs=Lists.newArrayList();
    nameValuePairs.add(new BasicNameValuePair("systeminfo",JSONValue.toJSONString(info)));
    request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response=httpClient.execute(request);
    if (response.getStatusLine().getStatusCode() != 201) {
      LOG.warn("Response code for system statistics was not 201, but " + response.getStatusLine().getStatusCode());
    }
  }
 catch (  Exception e) {
    LOG.warn("Could not send system statistics.",e);
  }
 finally {
    httpClient.getConnectionManager().shutdown();
  }
}
 

Example 47

From project gxa, under directory /annotator/src/main/java/uk/ac/ebi/gxa/annotator/loader/util/.

Source file: HttpClientHelper.java

  15 
vote

public static InputStream httpPost(HttpClient httpClient,URI uri,List<? extends NameValuePair> params) throws IOException {
  HttpPost httppost=new HttpPost(uri);
  httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
  HttpResponse response=httpClient.execute(httppost);
  int statusCode=response.getStatusLine().getStatusCode();
  if (statusCode != HttpStatus.SC_OK) {
    throw new IOException("Server returned invalid response: [status_code = " + statusCode + "; url = "+ uri+ "]");
  }
  return response.getEntity().getContent();
}
 

Example 48

From project hqapi, under directory /hqapi1/src/main/java/org/hyperic/hq/hqapi1/.

Source file: HQConnection.java

  15 
vote

public <T>T doPost(String path,Map<String,String[]> params,ResponseHandler<T> responseHandler) throws IOException {
  HttpPost post=new HttpPost();
  if (params != null && !params.isEmpty()) {
    List<NameValuePair> postParams=new ArrayList<NameValuePair>();
    for (    Map.Entry<String,String[]> entry : params.entrySet()) {
      for (      String value : entry.getValue()) {
        postParams.add(new BasicNameValuePair(entry.getKey(),value));
      }
    }
    post.setEntity(new UrlEncodedFormEntity(postParams,"UTF-8"));
  }
  return runMethod(post,buildUri(path,params),responseHandler);
}