Java Code Examples for org.apache.http.client.entity.UrlEncodedFormEntity
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 droidgiro-android, under directory /src/se/droidgiro/scanner/.
Source file: CloudClient.java

public static boolean postFields(List<NameValuePair> fields) throws Exception { DefaultHttpClient client=new DefaultHttpClient(); URI uri=new URI(INVOICES_URL); Log.e(TAG,"" + uri.toString()); HttpPost post=new HttpPost(uri); UrlEncodedFormEntity entity=new UrlEncodedFormEntity(fields,"UTF-8"); post.setEntity(entity); HttpResponse res=client.execute(post); return (res.getStatusLine().getStatusCode() == 201 ? true : false); }
Example 2
From project 2Degrees-Toolbox, under directory /Toolbox/src/biz/shadowservices/DegreesToolbox/.
Source file: HttpPoster.java

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 3
From project Amantech, under directory /Android/cloudLogin/src/com/cloude/entropin/.
Source file: GAEConnector.java

/** */ 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 4
From project androidquery, under directory /demo/src/com/androidquery/test/async/.
Source file: AjaxLoadingActivity.java

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

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 aranea, under directory /webapp/src/test/java/no/dusken/aranea/integration/test/.
Source file: AbstractIntegrationTest.java

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 7
From project azure4j-blog-samples, under directory /ACSManagementService/src/com/persistent/azure/acs/.
Source file: ACSAuthenticationHelper.java

/** * 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 8
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 9
From project httpbuilder, under directory /src/main/java/groovyx/net/http/.
Source file: EncoderRegistry.java

public UrlEncodedFormEntity encodeForm(Map<?,?> params,Object contentType) throws UnsupportedEncodingException { List<NameValuePair> paramList=new ArrayList<NameValuePair>(); for ( Object key : params.keySet()) { Object val=params.get(key); if (val instanceof List<?>) for ( Object subVal : (List<?>)val) paramList.add(new BasicNameValuePair(key.toString(),(subVal == null) ? "" : subVal.toString())); else paramList.add(new BasicNameValuePair(key.toString(),(val == null) ? "" : val.toString())); } UrlEncodedFormEntity e=new UrlEncodedFormEntity(paramList,charset.name()); if (contentType != null) e.setContentType(contentType.toString()); return e; }
Example 10
From project memcached-session-manager, under directory /core/src/test/java/de/javakaffee/web/msm/integration/.
Source file: TestUtils.java

private static UrlEncodedFormEntity createFormEntity(final Map<String,String> params) throws UnsupportedEncodingException { final List<NameValuePair> parameters=new ArrayList<NameValuePair>(); for ( final Map.Entry<String,String> param : params.entrySet()) { parameters.add(new BasicNameValuePair(param.getKey(),param.getValue())); } final UrlEncodedFormEntity entity=new UrlEncodedFormEntity(parameters,HTTP.UTF_8); return entity; }
Example 11
From project mylyn.builds, under directory /org.eclipse.mylyn.hudson.core/src/org/eclipse/mylyn/internal/hudson/core/client/.
Source file: HudsonLoginForm.java

public UrlEncodedFormEntity createEntity() throws UnsupportedEncodingException { List<NameValuePair> requestParameters=new ArrayList<NameValuePair>(); requestParameters.add(new BasicNameValuePair("j_username",j_username)); requestParameters.add(new BasicNameValuePair("j_password",j_password)); requestParameters.add(new BasicNameValuePair("from",from)); requestParameters.add(new BasicNameValuePair("json",new Gson().toJson(this))); requestParameters.add(new BasicNameValuePair("Submit","log in")); UrlEncodedFormEntity entity=new UrlEncodedFormEntity(requestParameters); return entity; }
Example 12
private JSONObject OAuthPost(String url) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, ClientProtocolException, IOException, IllegalStateException, JSONException { String[] oauth_tokens=getOAuthTokens(); consumer.setTokenWithSecret(oauth_tokens[0],oauth_tokens[1]); HttpPost req=new HttpPost(url); UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"UTF-8"); req.setEntity(entity); consumer.sign(req); HttpResponse response=client.execute(req); JSONObject result=new JSONObject(convertToString(response.getEntity().getContent())); params.clear(); return result; }
Example 13
From project basiclti-portlet, under directory /src/main/java/au/edu/anu/portal/portlets/basiclti/support/.
Source file: HttpSupport.java

/** * 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 14
From project bbb-java, under directory /src/main/java/org/mconf/web/.
Source file: Authentication.java

/** * 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 15
From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/goodreads/api/.
Source file: ReviewUpdateHandler.java

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 16
From project caustic, under directory /implementation/browser-apache/src/net/caustic/http/.
Source file: ApacheBrowser.java

/** * 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 17
From project DeskSMS, under directory /DeskSMS/src/com/koushikdutta/desktopsms/.
Source file: TickleServiceHelper.java

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 18
From project DigitbooksExamples, under directory /DigitbooksExamples/src/fr/digitbooks/android/examples/chapitre08/.
Source file: RateDigitbooksActivity.java

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

/** * 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 20
public void retrieveAccessToken(String username,String password) throws OAuthStoreException, ClientProtocolException, IOException, ResponseException { HttpClient client=new DefaultHttpClient(); HttpPost request=new HttpPost(BASE_URL + "/access_token"); CommonsHttpOAuthConsumer consumer=new CommonsHttpOAuthConsumer(CONSUMER_KEY,CONSUMER_SECRET); List<BasicNameValuePair> params=Arrays.asList(new BasicNameValuePair("x_auth_username",username),new BasicNameValuePair("x_auth_password",password),new BasicNameValuePair("x_auth_mode","client_auth")); UrlEncodedFormEntity entity=null; try { entity=new UrlEncodedFormEntity(params,HTTP.UTF_8); } catch ( UnsupportedEncodingException e) { throw new RuntimeException("wtf"); } request.setEntity(entity); try { consumer.sign(request); } catch ( OAuthMessageSignerException e) { e.printStackTrace(); } catch ( OAuthExpectationFailedException e) { e.printStackTrace(); } catch ( OAuthCommunicationException e) { e.printStackTrace(); } HttpResponse response=client.execute(request); String responseString=Response.entityToString(response.getEntity()); String[] tmp=TextUtils.split(responseString,"&"); if (tmp.length < 2) { Log.e(TAG,"something wrong with access token response: " + responseString); return; } String token=tmp[0].replace("oauth_token=",""); String tokenSerect=tmp[1].replace("oauth_token_secret=",""); mAccessToken=new OAuthAccessToken(token,tokenSerect); storeAccessToken(); logger.info("retrieve access token with request token " + mConsumer.getToken() + " "+ mAccessToken+ " "+ mProvider.getAccessTokenEndpointUrl()); }
Example 21
From project FlipDroid, under directory /app/src/com/goal98/flipdroid2/client/.
Source file: OAuth.java

public HttpResponse SignRequest(String token,String tokenSecret,String url,List params){ HttpPost post=new HttpPost(url); try { post.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8)); } catch ( UnsupportedEncodingException e) { e.printStackTrace(); } post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,false); return SignRequest(token,tokenSecret,post); }
Example 22
From project GraduationProject, under directory /G-Card/src/Hello/Tab/Widget/.
Source file: AppEngineClient.java

private HttpResponse makeRequestNoRetry(String urlPath,List<NameValuePair> params,boolean newToken) throws Exception { Account account=new Account(mAccountName,"com.google"); String authToken=getAuthToken(mContext,account); if (newToken) { AccountManager accountManager=AccountManager.get(mContext); accountManager.invalidateAuthToken(account.type,authToken); authToken=getAuthToken(mContext,account); } DefaultHttpClient client=new DefaultHttpClient(); String continueURL=BASE_URL; URI uri=new URI(AUTH_URL + "?continue=" + URLEncoder.encode(continueURL,"UTF-8")+ "&auth="+ authToken); HttpGet method=new HttpGet(uri); final HttpParams getParams=new BasicHttpParams(); HttpClientParams.setRedirecting(getParams,false); method.setParams(getParams); HttpResponse res=client.execute(method); Header[] headers=res.getHeaders("Set-Cookie"); if (res.getStatusLine().getStatusCode() != 302 || headers.length == 0) { return res; } String ascidCookie=null; for ( Header header : headers) { if (header.getValue().indexOf("ACSID=") >= 0) { String value=header.getValue(); String[] pairs=value.split(";"); ascidCookie=pairs[0]; } } uri=new URI(BASE_URL + urlPath); HttpPost post=new HttpPost(uri); UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"UTF-8"); post.setEntity(entity); post.setHeader("Cookie",ascidCookie); post.setHeader("X-Same-Domain","1"); res=client.execute(post); return res; }
Example 23
From project gxa, under directory /annotator/src/main/java/uk/ac/ebi/gxa/annotator/loader/util/.
Source file: HttpClientHelper.java

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 24
From project hqapi, under directory /hqapi1/src/main/java/org/hyperic/hq/hqapi1/.
Source file: HQConnection.java

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); }
Example 25
From project Locast-Android, under directory /src/edu/mit/mobile/android/locast/net/.
Source file: NetworkClient.java

/** * Makes a request to pair the device with the server. The server sends back a set of credentials which are then stored for making further queries. * @param pairCode the unique code that is provided by the server. * @return true if pairing process was successful, otherwise false. * @throws IOException * @throws JSONException * @throws RecordStoreException * @throws NetworkProtocolException */ public boolean pairDevice(String pairCode) throws IOException, JSONException, NetworkProtocolException { final DefaultHttpClient hc=new DefaultHttpClient(); hc.addRequestInterceptor(REMOVE_EXPECTATIONS); final HttpPost r=new HttpPost(getFullUrlAsString(PATH_PAIR)); final List<BasicNameValuePair> parameters=new ArrayList<BasicNameValuePair>(); parameters.add(new BasicNameValuePair("auth_secret",pairCode)); r.setEntity(new UrlEncodedFormEntity(parameters)); r.setHeader("Content-Type",URLEncodedUtils.CONTENT_TYPE); final HttpResponse c=hc.execute(r); checkStatusCode(c,false); return true; }
Example 26
From project LRJavaLib, under directory /src/com/navnorth/learningregistry/.
Source file: LRClient.java

public static String executeHttpPost(String url,ArrayList postParameters) throws Exception { BufferedReader in=null; try { URI uri=URIfromURLString(url); HttpClient client=getHttpClient(uri.getScheme()); HttpPost request=new HttpPost(uri); UrlEncodedFormEntity formEntity=new UrlEncodedFormEntity(postParameters); request.setEntity(formEntity); HttpResponse response=client.execute(request); in=new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb=new StringBuffer(""); String line=""; String NL=System.getProperty("line.separator"); while ((line=in.readLine()) != null) { sb.append(line + NL); } in.close(); String result=sb.toString(); return result; } finally { if (in != null) { try { in.close(); } catch ( IOException e) { e.printStackTrace(); } } } }
Example 27
From project milton, under directory /milton/milton-client/src/main/java/com/ettrema/httpclient/.
Source file: Host.java

/** * POSTs the variables and returns the body * @param url - fully qualified and encoded URL to post to * @param params * @return */ public String doPost(String url,Map<String,String> params) throws com.ettrema.httpclient.HttpException, NotAuthorizedException, ConflictException, BadRequestException, NotFoundException { notifyStartRequest(); HttpPost m=new HttpPost(url); List<NameValuePair> formparams=new ArrayList<NameValuePair>(); for ( Entry<String,String> entry : params.entrySet()) { formparams.add(new BasicNameValuePair(entry.getKey(),entry.getValue())); } UrlEncodedFormEntity entity; try { entity=new UrlEncodedFormEntity(formparams); } catch ( UnsupportedEncodingException ex) { throw new RuntimeException(ex); } m.setEntity(entity); try { ByteArrayOutputStream bout=new ByteArrayOutputStream(); int res=Utils.executeHttpWithStatus(client,m,bout); Utils.processResultCode(res,url); return bout.toString(); } catch ( HttpException ex) { throw new RuntimeException(ex); } catch ( IOException ex) { throw new RuntimeException(ex); } finally { notifyFinishRequest(); } }
Example 28
From project milton2, under directory /milton-client/src/main/java/io/milton/httpclient/.
Source file: Host.java

/** * POSTs the variables and returns the body * @param url - fully qualified and encoded URL to post to * @param params * @return - the body of the response */ public String doPost(String url,Map<String,String> params) throws io.milton.httpclient.HttpException, NotAuthorizedException, ConflictException, BadRequestException, NotFoundException { notifyStartRequest(); HttpPost m=new HttpPost(url); List<NameValuePair> formparams=new ArrayList<NameValuePair>(); for ( Entry<String,String> entry : params.entrySet()) { formparams.add(new BasicNameValuePair(entry.getKey(),entry.getValue())); } UrlEncodedFormEntity entity; try { entity=new UrlEncodedFormEntity(formparams); } catch ( UnsupportedEncodingException ex) { throw new RuntimeException(ex); } m.setEntity(entity); try { ByteArrayOutputStream bout=new ByteArrayOutputStream(); int res=Utils.executeHttpWithStatus(client,m,bout); Utils.processResultCode(res,url); return bout.toString(); } catch ( HttpException ex) { throw new RuntimeException(ex); } catch ( IOException ex) { throw new RuntimeException(ex); } finally { notifyFinishRequest(); } }
Example 29
From project Notes, under directory /src/net/micode/notes/gtask/remote/.
Source file: GTaskClient.java

private JSONObject postRequest(JSONObject js) throws NetworkFailureException { if (!mLoggedin) { Log.e(TAG,"please login first"); throw new ActionFailureException("not logged in"); } HttpPost httpPost=createHttpPost(); try { LinkedList<BasicNameValuePair> list=new LinkedList<BasicNameValuePair>(); list.add(new BasicNameValuePair("r",js.toString())); UrlEncodedFormEntity entity=new UrlEncodedFormEntity(list,"UTF-8"); httpPost.setEntity(entity); HttpResponse response=mHttpClient.execute(httpPost); String jsString=getResponseContent(response.getEntity()); return new JSONObject(jsString); } catch ( ClientProtocolException e) { Log.e(TAG,e.toString()); e.printStackTrace(); throw new NetworkFailureException("postRequest failed"); } catch ( IOException e) { Log.e(TAG,e.toString()); e.printStackTrace(); throw new NetworkFailureException("postRequest failed"); } catch ( JSONException e) { Log.e(TAG,e.toString()); e.printStackTrace(); throw new ActionFailureException("unable to convert response content to jsonobject"); } catch ( Exception e) { Log.e(TAG,e.toString()); e.printStackTrace(); throw new ActionFailureException("error occurs when posting request"); } }
Example 30
From project OAuth2Android, under directory /src/org/gerstner/oauth2android/common/.
Source file: Connection.java

/** * Makes a standard http post request. The list of NameValuePairs can contain all parameters and parameter designations for the request. * @param parameterList * @param url * @return <code>Response</code> with the servers response * @throws UnsupportedEncodingException * @throws IOException */ public static Response httpPostRequest(List<NameValuePair> parameterList,String url) throws InvalidRequestException, InvalidClientException, InvalidGrantException, UnauthorizedClientException, UnsupportedGrantTypeException, InvalidScopeException, OAuthException, IOException { HttpClient httpclient=new DefaultHttpClient(); HttpPost httpPost=new HttpPost(url); try { httpPost.setEntity(new UrlEncodedFormEntity(parameterList)); } catch ( UnsupportedEncodingException ex) { } Response response=new Response(httpclient.execute(httpPost)); response.setRequestUrl(EntityUtils.toString(httpPost.getEntity())); return response; }
Example 31
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 32
public AuthenticateResponse authenticateToken(String serverUrl,String username,String password,String client){ final boolean GZIP=false; String url=serverUrl + AUTHENTICATE_TOKEN_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 33
From project OpenMEAP, under directory /java-shared/openmeap-shared-jdk5/src/com/openmeap/http/.
Source file: HttpRequestExecuterImpl.java

public HttpResponse postData(String url,Hashtable getParams,Hashtable postParams) throws HttpRequestException { try { List<NameValuePair> nameValuePairs=createNameValuePairs(postParams); UrlEncodedFormEntity entity=new UrlEncodedFormEntity(nameValuePairs,FormConstants.CHAR_ENC_DEFAULT); entity.setContentType(FormConstants.CONT_TYPE_DEFAULT); HttpPost httpPost=new HttpPost(createUrl(url,getParams)); httpPost.setHeader(FormConstants.CONTENT_TYPE,FormConstants.CONT_TYPE_DEFAULT); httpPost.setHeader(FormConstants.USERAGENT,FormConstants.USERAGENT_DEFAULT); httpPost.setEntity(entity); return execute(httpPost); } catch ( Exception e) { throw new HttpRequestException(e); } }
Example 34
From project OpenTripPlanner-for-Android, under directory /src/de/mastacode/http/.
Source file: Http.java

@Override protected HttpUriRequest createRequest() throws IOException { final HttpPost request=new HttpPost(url); if (data != null) { entity=new UrlEncodedFormEntity(data,charset); } request.setEntity(entity); return request; }
Example 35
From project org.ops4j.pax.web, under directory /itest/src/test/java/org/ops4j/pax/web/itest/.
Source file: ITestBase.java

protected void testPost(String path,List<NameValuePair> nameValuePairs,String expectedContent,int httpRC) throws ClientProtocolException, IOException { HttpPost post=new HttpPost(path); post.setEntity(new UrlEncodedFormEntity((List<NameValuePair>)nameValuePairs)); HttpResponse response=httpclient.execute(post); assertEquals("HttpResponseCode",httpRC,response.getStatusLine().getStatusCode()); if (expectedContent != null) { String responseBodyAsString=EntityUtils.toString(response.getEntity()); assertTrue(responseBodyAsString.contains(expectedContent)); } }
Example 36
From project rain-workload-toolkit, under directory /src/radlab/rain/workload/bookingHotspots/.
Source file: BookingOperation.java

public boolean processBookHotelButton() throws Throwable { String viewHotelFinalUrl=this._http.getFinalUrl(); StringBuilder viewHotelResponse=this._http.getResponseBuffer(); if (this._http.getStatusCode() != 200) { this.debugTrace("GET view hotel result status: " + this._http.getStatusCode()); return false; } if (viewHotelResponse.indexOf("value=\"Book Hotel\"") == -1) { this.debugTrace("GET did not display a view hotel result page."); this.debugTrace(viewHotelResponse.toString()); return false; } HttpPost bookHotelPost=new HttpPost(viewHotelFinalUrl); this.trace(this.getGenerator().getCurrentUser() + " POST " + viewHotelFinalUrl); String viewState=this.getViewStateFromResponse(viewHotelResponse); List<NameValuePair> formParams=new ArrayList<NameValuePair>(); formParams.add(new BasicNameValuePair("hotel","hotel")); formParams.add(new BasicNameValuePair("hotel:book","Book Hotel")); formParams.add(new BasicNameValuePair("javax.faces.ViewState",viewState)); UrlEncodedFormEntity entity=new UrlEncodedFormEntity(formParams,"UTF-8"); bookHotelPost.setEntity(entity); StringBuilder bookHotelResponse=this._http.fetch(bookHotelPost); if (this._http.getStatusCode() != 200) { this.debugTrace("POST book hotel status: " + this._http.getStatusCode()); return false; } if (this._http.getFinalUrl().indexOf("/login") > 0) { this.debugTrace("POST book hotel redirected to a Login form page."); return true; } if (bookHotelResponse.indexOf("<legend>Book Hotel</legend>") > 0) { this.debugTrace("Success - Response contains a Book Hotel page!"); return true; } this.debugTrace("ERROR - book hotel received an unexpected response page."); this.debugTrace(bookHotelResponse.toString()); return false; }
Example 37
From project ratebeer-for-Android, under directory /RateBeerForAndroid/src/com/ratebeer/android/api/.
Source file: HttpHelper.java

public static String makeRBPost(String url,List<? extends NameValuePair> parameters,int expectedHttpCode) throws ClientProtocolException, IOException { ensureClient(); HttpPost post=new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(parameters)); HttpResponse response=httpClient.execute(post); if (response.getStatusLine().getStatusCode() == expectedHttpCode) { return getResponseString(response.getEntity().getContent()); } throw new IOException("ratebeer.com offline?"); }
Example 38
From project ratebeerforandroid, under directory /RateBeerForAndroid/src/com/ratebeer/android/api/.
Source file: HttpHelper.java

public static String makeRBPost(String url,List<? extends NameValuePair> parameters,int expectedHttpCode) throws ClientProtocolException, IOException { ensureClient(); HttpPost post=new HttpPost(url); post.setEntity(new UrlEncodedFormEntity(parameters)); HttpResponse response=httpClient.execute(post); if (response.getStatusLine().getStatusCode() == expectedHttpCode) { return getResponseString(response.getEntity().getContent()); } throw new IOException("ratebeer.com offline?"); }
Example 39
From project reader, under directory /src/com/quietlycoding/android/reader/util/api/.
Source file: Authentication.java

/** * This method returns back to the caller a proper authentication token to use with the other API calls to Google Reader. * @param user - the Google username * @param pass - the Google password * @return sid - the returned authentication token for use with the API. */ public static String getAuthToken(String user,String pass){ final NameValuePair username=new BasicNameValuePair("Email",user); final NameValuePair password=new BasicNameValuePair("Passwd",pass); final NameValuePair service=new BasicNameValuePair("service","reader"); final List<NameValuePair> pairs=new ArrayList<NameValuePair>(); pairs.add(username); pairs.add(password); pairs.add(service); try { final DefaultHttpClient client=new DefaultHttpClient(); final HttpPost post=new HttpPost(AUTH_URL); final UrlEncodedFormEntity entity=new UrlEncodedFormEntity(pairs); post.setEntity(entity); final HttpResponse response=client.execute(post); final HttpEntity respEntity=response.getEntity(); Log.d(TAG,"Server Response: " + response.getStatusLine()); final InputStream in=respEntity.getContent(); final BufferedReader reader=new BufferedReader(new InputStreamReader(in)); String line=null; String result=null; while ((line=reader.readLine()) != null) { if (line.startsWith("SID")) { result=line.substring(line.indexOf("=") + 1); } } reader.close(); client.getConnectionManager().shutdown(); return result; } catch ( final Exception e) { Log.d(TAG,"Exception caught:: " + e.toString()); return null; } }
Example 40
From project rest-assured, under directory /rest-assured/src/main/java/com/jayway/restassured/internal/http/.
Source file: EncoderRegistry.java

/** * Set the request body as a url-encoded list of parameters. This is typically used to simulate a HTTP form POST. For multi-valued parameters, enclose the values in a list, e.g. <pre>[ key1 : ['val1', 'val2'], key2 : 'etc.' ]</pre> * @param params * @return an {@link HttpEntity} encapsulating this request data * @throws UnsupportedEncodingException */ public UrlEncodedFormEntity encodeForm(Map<?,?> params) throws UnsupportedEncodingException { List<NameValuePair> paramList=new ArrayList<NameValuePair>(); for ( Object key : params.keySet()) { Object val=params.get(key); if (val instanceof List) for ( Object subVal : (List)val) paramList.add(new BasicNameValuePair(key.toString(),(subVal == null) ? "" : subVal.toString())); else paramList.add(new BasicNameValuePair(key.toString(),(val == null) ? "" : val.toString())); } return new UrlEncodedFormEntity(paramList,charset.name()); }
Example 41
From project RT-REST, under directory /src/main/java/de/boksa/rt/rest/.
Source file: RTRESTClient.java

private RTRESTResponse getResponse(String url,List<NameValuePair> params) throws IOException { HttpPost postRequest=new HttpPost(this.getRestInterfaceBaseURL() + url); UrlEncodedFormEntity postEntity=new UrlEncodedFormEntity(params,HTTP.UTF_8); postEntity.setContentType("application/x-www-form-urlencoded"); postRequest.setEntity(postEntity); HttpResponse httpResponse=this.httpClient.execute(postRequest); String responseBody=IOUtils.toString(httpResponse.getEntity().getContent(),HTTP.UTF_8); Matcher matcher=PATTERN_RESPONSE_BODY.matcher(responseBody); if (matcher.matches()) { RTRESTResponse response=new RTRESTResponse(); response.setVersion(matcher.group(1)); response.setStatusCode(Long.valueOf(matcher.group(2))); response.setStatusMessage(matcher.group(3)); response.setBody(matcher.group(4).trim()); return response; } else { System.err.println("not matched"); } return new RTRESTResponse(); }
Example 42
From project sakai-connector-portlet, under directory /src/main/java/au/edu/anu/portal/portlets/sakaiconnector/support/.
Source file: HttpSupport.java

/** * 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 43
From project SASAbus, under directory /src/it/sasabz/android/sasabus/classes/.
Source file: SasabusHTTP.java

/** * Requesting data via get-request using the apache http-classes * @throws IOException * @throws ClientProtocolException */ public String postData(List<NameValuePair> params) throws ClientProtocolException, IOException { HttpClient httpclient=new DefaultHttpClient(); HttpPost post=new HttpPost(hostname); Log.v("HOSTNAME",hostname); post.setEntity(new UrlEncodedFormEntity(params)); HttpResponse rp=httpclient.execute(post); String responseBody=null; if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { responseBody=EntityUtils.toString(rp.getEntity()); } return responseBody; }
Example 44
From project ServiceFramework, under directory /src/net/csdn/modules/transport/.
Source file: DefaultHttpTransportService.java

public SResponse post(Url url,Map data){ HttpPost post=null; try { post=new HttpPost(url.toURI()); UrlEncodedFormEntity urlEncodedFormEntity=new UrlEncodedFormEntity(mapToNameValuesPairs(data),charset); post.setHeader(content_type.v1(),content_type.v2()); post.setEntity(urlEncodedFormEntity); HttpResponse response=httpClient.execute(post); return new SResponse(response.getStatusLine().getStatusCode(),EntityUtils.toString(response.getEntity(),charset),url); } catch ( IOException e) { logger.error("Error when remote search url:[{}] ",url.toString()); return null; } finally { if (post != null) post.abort(); } }
Example 45
From project SocialLib, under directory /src/com/expertiseandroid/lib/sociallib/connectors/.
Source file: TwitterConnector.java

private ReadableResponse signedPostRequest(String request,List<NameValuePair> bodyParams) throws OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException, ClientProtocolException, IOException { HttpClient client=new DefaultHttpClient(); HttpPost post=new HttpPost(request); post.setEntity(new UrlEncodedFormEntity(bodyParams,HTTP.UTF_8)); post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,false); httpOauthConsumer.sign(post); HttpResponse response=client.execute(post); return new HttpResponseWrapper(response); }
Example 46
From project Something-Awful-Android, under directory /application/src/com/ferg/awfulapp/network/.
Source file: NetworkUtils.java

public static TagNode post(String aUrl,HashMap<String,String> aParams) throws Exception { TagNode response=null; Log.i(TAG,aUrl); HttpPost httpPost=new HttpPost(aUrl); httpPost.setEntity(new UrlEncodedFormEntity(getPostParameters(aParams))); HttpResponse httpResponse=sHttpClient.execute(httpPost); HttpEntity entity=httpResponse.getEntity(); if (entity != null) { response=sCleaner.clean(new InputStreamReader(entity.getContent(),CHARSET)); } return response; }
Example 47
From project sparsemapcontent, under directory /extensions/resource/src/test/java/uk/co/tfd/sm/integration/resource/.
Source file: DataTypesTest.java

private JsonObject testType(String type,Object testsingle,Object[] testproperty,Object testarray) throws AuthenticationException, ClientProtocolException, IOException { String resource="/" + this.getClass().getName() + "/test"+ type+ "Type"+ System.currentTimeMillis(); String resourceUrl=IntegrationServer.BASEURL + resource; HttpPost post=new HttpPost(resourceUrl); UsernamePasswordCredentials creds=new UsernamePasswordCredentials(ADMIN_USER,ADMIN_PASSWORD); post.addHeader(new BasicScheme().authenticate(creds,post)); List<BasicNameValuePair> v=Lists.newArrayList(); v.add(new BasicNameValuePair("testsingle@" + type,String.valueOf(testsingle))); for ( Object o : testproperty) { v.add(new BasicNameValuePair("testproperty@" + type,String.valueOf(o))); } v.add(new BasicNameValuePair("testarray[]@" + type,String.valueOf(testarray))); UrlEncodedFormEntity form=new UrlEncodedFormEntity(v); post.setEntity(form); post.setHeader("Referer","/integratriontest/" + this.getClass().getName()); httpTestUtils.execute(post,200,APPLICATION_JSON); JsonObject json=JsonTestUtils.toJsonObject(httpTestUtils.get(resourceUrl + ".pp.json",200,APPLICATION_JSON)); JsonTestUtils.checkProperty(json,"_path",resource); return json; }
Example 48
From project subsonic, under directory /subsonic-main/src/main/java/net/sourceforge/subsonic/service/.
Source file: AudioScrobblerService.java

private String[] executePostRequest(String url,Map<String,String> parameters) throws IOException { List<NameValuePair> params=new ArrayList<NameValuePair>(); for ( Map.Entry<String,String> entry : parameters.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(),entry.getValue())); } HttpPost request=new HttpPost(url); request.setEntity(new UrlEncodedFormEntity(params,StringUtil.ENCODING_UTF8)); return executeRequest(request); }
Example 49
From project subsonic_1, under directory /subsonic-main/src/main/java/net/sourceforge/subsonic/service/.
Source file: AudioScrobblerService.java

private String[] executePostRequest(String url,Map<String,String> parameters) throws IOException { List<NameValuePair> params=new ArrayList<NameValuePair>(); for ( Map.Entry<String,String> entry : parameters.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(),entry.getValue())); } HttpPost request=new HttpPost(url); request.setEntity(new UrlEncodedFormEntity(params,StringUtil.ENCODING_UTF8)); return executeRequest(request); }
Example 50
From project subsonic_2, under directory /subsonic-main/src/main/java/net/sourceforge/subsonic/service/.
Source file: AudioScrobblerService.java

private String[] executePostRequest(String url,Map<String,String> parameters) throws IOException { List<NameValuePair> params=new ArrayList<NameValuePair>(); for ( Map.Entry<String,String> entry : parameters.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(),entry.getValue())); } HttpPost request=new HttpPost(url); request.setEntity(new UrlEncodedFormEntity(params,StringUtil.ENCODING_UTF8)); return executeRequest(request); }
Example 51
From project Supersonic, under directory /subsonic-main/src/main/java/net/sourceforge/subsonic/service/.
Source file: AudioScrobblerService.java

private String[] executePostRequest(String url,Map<String,String> parameters) throws IOException { List<NameValuePair> params=new ArrayList<NameValuePair>(); for ( Map.Entry<String,String> entry : parameters.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(),entry.getValue())); } HttpPost request=new HttpPost(url); request.setEntity(new UrlEncodedFormEntity(params,StringUtil.ENCODING_UTF8)); return executeRequest(request); }
Example 52
From project usergrid-stack, under directory /rest/src/test/java/org/usergrid/rest/filters/.
Source file: ContentTypeResourceTest.java

/** * Tests that application/x-www-url-form-encoded works correctly * @throws * @throws Exception */ @Test public void formEncodedContentType() throws Exception { List<NameValuePair> pairs=new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("organization","formContentOrg")); pairs.add(new BasicNameValuePair("username","formContentOrg")); pairs.add(new BasicNameValuePair("name","Test User")); pairs.add(new BasicNameValuePair("email",UUIDUtils.newTimeUUID() + "@usergrid.org")); pairs.add(new BasicNameValuePair("password","foobar")); UrlEncodedFormEntity entity=new UrlEncodedFormEntity(pairs,"UTF-8"); DefaultHttpClient client=new DefaultHttpClient(); HttpHost host=new HttpHost(super.getBaseURI().getHost(),super.getBaseURI().getPort()); HttpPost post=new HttpPost("/management/orgs"); post.setEntity(entity); post.setHeader(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_FORM_URLENCODED); HttpResponse rsp=client.execute(host,post); printResponse(rsp); assertEquals(200,rsp.getStatusLine().getStatusCode()); }
Example 53
From project Vega, under directory /platform/com.subgraph.vega.scanner/src/com/subgraph/vega/impl/scanner/requests/.
Source file: PostParameterRequestBuilder.java

private HttpEntity createParameterEntity(List<NameValuePair> parameters){ try { return new UrlEncodedFormEntity(parameters,"UTF-8"); } catch ( UnsupportedEncodingException e) { throw new RuntimeException("Failed to encode form parameters.",e); } }
Example 54
From project websms-api, under directory /src/de/ub0r/android/websms/connector/common/.
Source file: Utils.java

/** * Add form data as {@link HttpEntity}. * @param formData form data * @return {@link HttpEntity} * @throws UnsupportedEncodingException UnsupportedEncodingException */ public final HttpEntity addFormParameter(final List<BasicNameValuePair> formData) throws UnsupportedEncodingException { HttpEntity he=null; if (formData != null) { he=new UrlEncodedFormEntity(formData,this.encoding); this.postData=he; } return he; }
Example 55
From project wip, under directory /src/main/java/fr/ippon/wip/http/request/.
Source file: PostRequestBuilder.java

public HttpRequestBase buildHttpRequest() throws URISyntaxException { URI uri=new URI(getRequestedURL()); HttpPost postRequest=new HttpPost(uri); if (parameterMap == null) return postRequest; List<NameValuePair> httpParams=new LinkedList<NameValuePair>(); for ( Map.Entry<String,String> entry : parameterMap.entries()) httpParams.add(new BasicNameValuePair(entry.getKey(),entry.getValue())); HttpEntity formEntity=new UrlEncodedFormEntity(httpParams,ContentType.APPLICATION_FORM_URLENCODED.getCharset()); postRequest.setEntity(formEntity); return postRequest; }
Example 56
From project zeitgeist-api, under directory /src/li/zeitgeist/api/.
Source file: ZeitgeistApi.java

/** * Creates urlencoded data from a pair list for POST requests. * @param postData * @return entity * @throws ZeitgeistError */ private HttpEntity createEntityByNameValueList(List<NameValuePair> postData) throws ZeitgeistError { try { return new UrlEncodedFormEntity(postData,"UTF-8"); } catch ( UnsupportedEncodingException e) { throw new ZeitgeistError("UnsupportedEncoding: " + e.getMessage()); } }
Example 57
From project accesointeligente, under directory /src/org/accesointeligente/server/robots/.
Source file: SIAC.java

@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 58
From project android-async-http, under directory /src/com/loopj/android/http/.
Source file: RequestParams.java

/** * Returns an HttpEntity containing all request parameters */ public HttpEntity getEntity(){ HttpEntity entity=null; if (!fileParams.isEmpty()) { SimpleMultipartEntity multipartEntity=new SimpleMultipartEntity(); for ( ConcurrentHashMap.Entry<String,String> entry : urlParams.entrySet()) { multipartEntity.addPart(entry.getKey(),entry.getValue()); } int currentIndex=0; int lastIndex=fileParams.entrySet().size() - 1; for ( ConcurrentHashMap.Entry<String,FileWrapper> entry : fileParams.entrySet()) { FileWrapper file=entry.getValue(); if (file.inputStream != null) { boolean isLast=currentIndex == lastIndex; if (file.contentType != null) { multipartEntity.addPart(entry.getKey(),file.getFileName(),file.inputStream,file.contentType,isLast); } else { multipartEntity.addPart(entry.getKey(),file.getFileName(),file.inputStream,isLast); } } currentIndex++; } entity=multipartEntity; } else { try { entity=new UrlEncodedFormEntity(getParamsList(),ENCODING); } catch ( UnsupportedEncodingException e) { e.printStackTrace(); } } return entity; }
Example 59
From project android-bankdroid, under directory /src/com/liato/bankdroid/banking/banks/.
Source file: Rikslunchen.java

@Override protected LoginPackage preLogin() throws BankException, ClientProtocolException, IOException { urlopen=new Urllib(true,true); List<NameValuePair> postData=new ArrayList<NameValuePair>(); postData.add(new BasicNameValuePair("c0-param0","string:" + password)); postData.add(new BasicNameValuePair("callCount","1")); postData.add(new BasicNameValuePair("windowName","")); postData.add(new BasicNameValuePair("c0-scriptName","cardUtil")); postData.add(new BasicNameValuePair("c0-methodName","getCardData")); postData.add(new BasicNameValuePair("c0-id","0")); postData.add(new BasicNameValuePair("batchId","1")); postData.add(new BasicNameValuePair("page","%2Friks-cp%2Fcheck_balance.html")); postData.add(new BasicNameValuePair("httpSessionId","")); postData.add(new BasicNameValuePair("scriptSessionId","")); HttpClient httpclient=new DefaultHttpClient(); HttpPost httppost=new HttpPost("http://www.rikslunchen.se/riks-cp/dwr/call/plaincall/cardUtil.getCardData.dwr"); httppost.setEntity(new UrlEncodedFormEntity(postData)); HttpResponse response=httpclient.execute(httppost); InputStream streamResponse=response.getEntity().getContent(); StringWriter writer=new StringWriter(); IOUtils.copy(streamResponse,writer); return new LoginPackage(urlopen,postData,writer.toString(),"http://www.rikslunchen.se/riks-cp/dwr/call/plaincall/cardUtil.getCardData.dwr"); }
Example 60
From project Android-SyncAdapter-JSON-Server-Example, under directory /src/com/example/android/samplesync/client/.
Source file: NetworkUtilities.java

/** * 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 61
From project andstatus, under directory /src/org/andstatus/app/net/.
Source file: ConnectionOAuth.java

@Override public JSONObject updateStatus(String message,String inReplyToId) throws ConnectionException { HttpPost post=new HttpPost(getApiUrl(apiEnum.STATUSES_UPDATE)); LinkedList<BasicNameValuePair> out=new LinkedList<BasicNameValuePair>(); out.add(new BasicNameValuePair("status",message)); if (!TextUtils.isEmpty(inReplyToId)) { out.add(new BasicNameValuePair("in_reply_to_status_id",inReplyToId)); } try { post.setEntity(new UrlEncodedFormEntity(out,HTTP.UTF_8)); } catch ( UnsupportedEncodingException e) { Log.e(TAG,e.toString()); } return postRequest(post); }
Example 62
From project andtweet, under directory /src/com/xorcode/andtweet/net/.
Source file: ConnectionOAuth.java

@Override public JSONObject updateStatus(String message,long inReplyToId) throws ConnectionException { HttpPost post=new HttpPost(STATUSES_UPDATE_URL); LinkedList<BasicNameValuePair> out=new LinkedList<BasicNameValuePair>(); out.add(new BasicNameValuePair("status",message)); if (inReplyToId > 0) { out.add(new BasicNameValuePair("in_reply_to_status_id",String.valueOf(inReplyToId))); } try { post.setEntity(new UrlEncodedFormEntity(out,HTTP.UTF_8)); } catch ( UnsupportedEncodingException e) { Log.e(TAG,e.toString()); } return postRequest(post); }
Example 63
From project AudioBox.fm-JavaLib, under directory /audiobox.fm-core/src/main/java/fm/audiobox/configurations/.
Source file: DefaultRequestMethod.java

@Override public Response send(boolean async,List<NameValuePair> params) throws ServiceException, LoginException { HttpEntity entity=null; if ((!isGET() && !isDELETE()) && params != null) { try { if (log.isInfoEnabled()) { StringBuffer sb=new StringBuffer(); for ( NameValuePair param : params) { sb.append("[" + param.getName() + ": '"+ param.getValue()+ "'], "); } log.info("Params: " + sb.toString()); } entity=new UrlEncodedFormEntity(params,HTTP.UTF_8); } catch ( UnsupportedEncodingException e) { log.error("An error occurred while instantiating UrlEncodedFormEntity",e); } } return send(async,entity); }
Example 64
From project BF3-Battlelog, under directory /src/com/ninetwozero/battlelog/http/.
Source file: RequestHandler.java

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 65
From project bookmarktodesktop-android-application, under directory /src/be/vbsteven/bmtodesk/.
Source file: BackgroundSharingService.java

/** * 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 66
From project BusFollower, under directory /src/net/argilo/busfollower/ocdata/.
Source file: OCTranspoDataFetcher.java

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 67
From project c2dm4j, under directory /src/main/java/org/whispercomm/c2dm4j/impl/.
Source file: C2dmHttpPost.java

private void initPostEntity(Message message){ List<NameValuePair> params=new ArrayList<NameValuePair>(); addParam(params,REGISTRATION_ID,message.getRegistrationId()); addParam(params,COLLAPSE_ID,message.getCollapseKey()); if (message.delayWhileIdle()) addParam(params,DELAY_WHILE_IDLE); Map<String,String> data=message.getData(); for ( String key : data.keySet()) { addParam(params,DATA_KEY_PREFIX + key,data.get(key)); } try { this.setEntity(new UrlEncodedFormEntity(params,"UTF-8")); } catch ( UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(),e); } }
Example 68
From project CityBikes, under directory /src/net/homelinux/penecoptero/android/citybikes/app/.
Source file: RESTHelper.java

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 69
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 70
From project DiscogsForAndroid, under directory /src/com/discogs/services/.
Source file: NetworkHelper.java

public String doHTTPPost(String uri,List<NameValuePair> nameValuePairs){ String response=null; HttpPost hTTPPost=new HttpPost(uri); try { hTTPPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); consumer.sign(hTTPPost); HttpResponse hTTPResponse=httpClient.execute(hTTPPost); response=EntityUtils.toString(hTTPResponse.getEntity()); Log.d("Discogs","Response: " + response); } catch ( MalformedURLException e) { e.printStackTrace(); } catch ( IOException e) { e.printStackTrace(); } catch ( OAuthMessageSignerException e) { e.printStackTrace(); } catch ( OAuthExpectationFailedException e) { e.printStackTrace(); } catch ( OAuthCommunicationException e) { e.printStackTrace(); } return response; }
Example 71
From project Gaggle, under directory /src/com/geeksville/location/.
Source file: LeonardoUpload.java

/** * 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 72
From project generic-store-for-android, under directory /src/com/wareninja/opensource/common/.
Source file: CustomBugSenseReportSender.java

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 73
From project gmarks-android, under directory /src/main/java/org/thomnichols/android/gmarks/.
Source file: BookmarksQueryService.java

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 74
From project graylog2-server, under directory /src/main/java/org/graylog2/systeminformation/.
Source file: Sender.java

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 75
From project httpClient, under directory /httpclient/src/examples/org/apache/http/examples/client/.
Source file: QuickStart.java

public static void main(String[] args) throws Exception { DefaultHttpClient httpclient=new DefaultHttpClient(); HttpGet httpGet=new HttpGet("http://targethost/homepage"); HttpResponse response1=httpclient.execute(httpGet); try { System.out.println(response1.getStatusLine()); HttpEntity entity1=response1.getEntity(); EntityUtils.consume(entity1); } finally { httpGet.releaseConnection(); } HttpPost httpPost=new HttpPost("http://targethost/login"); List<NameValuePair> nvps=new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username","vip")); nvps.add(new BasicNameValuePair("password","secret")); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); HttpResponse response2=httpclient.execute(httpPost); try { System.out.println(response2.getStatusLine()); HttpEntity entity2=response2.getEntity(); EntityUtils.consume(entity2); } finally { httpPost.releaseConnection(); } }
Example 76
From project java-maven-tests, under directory /src/web-jdo/gdata-webapp-test/src/main/java/com/mysite/gdatatest/util/.
Source file: GoogleUtil.java

public static String fetchAccessToken(String code,Map<String,String> appProperties) throws IOException { final HttpClient httpClient=new DefaultHttpClient(); final HttpPost post=new HttpPost("https://accounts.google.com/o/oauth2/token"); final HttpEntity entity=new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("client_id",appProperties.get("google.clientId")),new BasicNameValuePair("client_secret",appProperties.get("google.clientSecret")),new BasicNameValuePair("redirect_uri","http://localhost:9090/gdata-webapp-test/oauth.do"),new BasicNameValuePair("grant_type","authorization_code"),new BasicNameValuePair("code",code))); post.setEntity(entity); final HttpResponse response=httpClient.execute(post); LOG.info("Status: {}",response.getStatusLine()); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { if (response.getEntity() != null) { final StringBuilder stringBuilder=new StringBuilder(); final String encoding="UTF-8"; final InputStream inputStream=response.getEntity().getContent(); try { final InputStreamReader reader=new InputStreamReader(inputStream,encoding); try { for (; ; ) { final char[] buffer=new char[1024]; final int charsRead=reader.read(buffer); if (charsRead <= 0) { break; } stringBuilder.append(buffer,0,charsRead); } } finally { reader.close(); } } finally { inputStream.close(); } final String contentStr=stringBuilder.toString(); return getAccessTokenValue(contentStr); } } return null; }
Example 77
From project lightbox-android-webservices, under directory /LightboxAndroidWebServices/src/com/lightbox/android/network/.
Source file: HttpHelper.java

private static HttpUriRequest addBodyToHttpRequest(HttpUriRequest request,Object body) throws IOException { if (body != null && request instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest entityEnclosingRequest=(HttpEntityEnclosingRequest)request; if (body instanceof Map) { Map<?,?> bodyMap=(Map<?,?>)body; entityEnclosingRequest.setEntity(new UrlEncodedFormEntity(mapToNameValueList(bodyMap),HTTP.UTF_8)); } else if (body instanceof HttpEntity) { HttpEntity entity=(HttpEntity)body; entityEnclosingRequest.setEntity(entity); } else { entityEnclosingRequest.setEntity(new StringEntity(body.toString(),HTTP.UTF_8)); } } return request; }
Example 78
From project Maimonides, under directory /src/com/codeko/apps/maimonides/cartero/.
Source file: SMSGestion.java

public boolean enviarSMS(String texto,ArrayList<String> numeros){ boolean ret=false; try { String control=System.currentTimeMillis() + ""; String hash=Cripto.md5(getClaveServicio() + control); String xml=getXML(texto,numeros); HttpPost post=new HttpPost(WEB); List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(3); nameValuePairs.add(new BasicNameValuePair("ent",getEntidad())); nameValuePairs.add(new BasicNameValuePair("control",control)); nameValuePairs.add(new BasicNameValuePair("hash",hash)); nameValuePairs.add(new BasicNameValuePair("op","enviarmensaje")); nameValuePairs.add(new BasicNameValuePair("archivo",xml)); post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"ISO-8859-1")); HttpResponse response=getCliente().execute(post); String textResp=EntityUtils.toString(response.getEntity()); if (response.getStatusLine().getStatusCode() == 200) { Logger.getLogger(SMSGestion.class.getName()).info(textResp); ret=textResp.toLowerCase().indexOf("error") == -1; } else { ret=false; Logger.getLogger(SMSGestion.class.getName()).log(Level.INFO,"{0}\n{1}",new Object[]{response.getStatusLine().getStatusCode(),textResp}); } } catch ( Exception ex) { Logger.getLogger(SMSGestion.class.getName()).log(Level.SEVERE,null,ex); ret=false; } return ret; }
Example 79
From project Mockey, under directory /src/java/com/mockey/model/.
Source file: RequestFromClient.java

private HttpEntity constructHttpPostBody(){ HttpEntity body; try { if (requestBody != null) { body=new StringEntity(requestBody); } else { List<NameValuePair> parameters=new ArrayList<NameValuePair>(); for ( Map.Entry<String,String[]> entry : this.parameters.entrySet()) { for ( String value : entry.getValue()) { parameters.add(new BasicNameValuePair(entry.getKey(),value)); } } body=new UrlEncodedFormEntity(parameters,HTTP.ISO_8859_1); } } catch ( UnsupportedEncodingException e) { throw new IllegalStateException("Unable to generate a POST from the incoming request",e); } return body; }
Example 80
From project MyHeath-Android, under directory /src/com/buaa/shortytall/network/.
Source file: AbstractNetWorkThread.java

protected String executePost(List<BasicNameValuePair> pairs) throws ClientProtocolException, IOException { setUrl(); if (mUrl == null) { return null; } HttpPost httpPost=new HttpPost(mUrl); httpPost.setEntity(new UrlEncodedFormEntity(pairs,HTTP.UTF_8)); HttpParams params=new BasicHttpParams(); HttpConnectionParams.setSoTimeout(params,TIMEOUT); HttpConnectionParams.setConnectionTimeout(params,TIMEOUT); HttpClientParams.setRedirecting(params,false); if (mHttpClient == null) { mHttpClient=new DefaultHttpClient(); } mHttpClient.setParams(params); DefaultCoookieStore cookieStore=DefaultCoookieStore.getInstance(MyHealth.getCurrentContext()); mHttpClient.setCookieStore(cookieStore); HttpResponse response=mHttpClient.execute(httpPost); cookieStore.saveCookies(MyHealth.getCurrentContext()); int statusCode=response.getStatusLine().getStatusCode(); if (statusCode == 200) { return EntityUtils.toString(response.getEntity()); } return null; }
Example 81
From project nevernote, under directory /src/cx/fbn/nevernote/threads/.
Source file: SyncRunner.java

private void downloadInkNoteImage(String guid,String authToken){ String urlBase=noteStoreUrl.replace("/edam/note/","/shard/") + "/res/" + guid+ ".ink?slice="; Integer slice=1; Resource r=conn.getNoteTable().noteResourceTable.getNoteResource(guid,false); conn.getInkImagesTable().expungeImage(r.getGuid()); int sliceCount=1 + ((r.getHeight() - 1) / 480); HttpClient http=new DefaultHttpClient(); for (int i=0; i < sliceCount; i++) { String url=urlBase + slice.toString(); HttpPost post=new HttpPost(url); post.getParams().setParameter("auth",authToken); List<NameValuePair> nvps=new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("auth",authToken)); try { post.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8)); } catch ( UnsupportedEncodingException e1) { e1.printStackTrace(); } try { HttpResponse response=http.execute(post); HttpEntity resEntity=response.getEntity(); InputStream is=resEntity.getContent(); QByteArray data=writeToFile(is); conn.getInkImagesTable().saveImage(guid,slice,data); } catch ( ClientProtocolException e) { e.printStackTrace(); } catch ( IOException e) { e.printStackTrace(); } slice++; } http.getConnectionManager().shutdown(); noteSignal.noteChanged.emit(r.getNoteGuid(),null); }
Example 82
From project open311-android, under directory /open311-android/src/gov/in/bloomington/georeporter/models/.
Source file: Open311.java

/** * POST new service request data to the endpoint * @param data * @return JSONObject */ public static JSONArray postServiceRequest(HashMap<String,String> data){ List<NameValuePair> pairs=new ArrayList<NameValuePair>(); for ( Map.Entry<String,String> entry : data.entrySet()) { pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue())); } if (mJurisdiction != null) { pairs.add(new BasicNameValuePair(JURISDICTION,mJurisdiction)); } if (mApiKey != null) { pairs.add(new BasicNameValuePair(API_KEY,mApiKey)); } HttpPost request=new HttpPost(mBaseUrl + "/requests.json"); JSONArray response=null; try { request.setEntity(new UrlEncodedFormEntity(pairs)); HttpResponse r=mClient.execute(request); response=new JSONArray(EntityUtils.toString(r.getEntity())); } catch ( UnsupportedEncodingException e) { e.printStackTrace(); } catch ( ClientProtocolException e) { e.printStackTrace(); } catch ( IOException e) { e.printStackTrace(); } catch ( ParseException e) { e.printStackTrace(); } catch ( JSONException e) { e.printStackTrace(); } return response; }
Example 83
From project openbicing, under directory /src/net/homelinux/penecoptero/android/openbicing/app/.
Source file: RESTHelper.java

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 84
From project PageTurner, under directory /src/main/java/net/nightwhistler/pageturner/sync/.
Source file: PageTurnerWebProgressService.java

@Override public void storeProgress(String fileName,int index,int progress,int percentage){ if (!config.isSyncEnabled()) { return; } String key=computeKey(fileName); HttpPost post=new HttpPost(BASE_URL + key); String filePart=fileName; if (fileName.indexOf("/") != -1) { filePart=fileName.substring(fileName.lastIndexOf('/')); } try { List<NameValuePair> pairs=new ArrayList<NameValuePair>(); pairs.add(new BasicNameValuePair("bookIndex","" + index)); pairs.add(new BasicNameValuePair("progress","" + progress)); pairs.add(new BasicNameValuePair("title",Integer.toHexString(filePart.hashCode()))); pairs.add(new BasicNameValuePair("deviceName",this.config.getDeviceName())); pairs.add(new BasicNameValuePair("percentage","" + percentage)); pairs.add(new BasicNameValuePair("userId",Integer.toHexString(this.config.getSynchronizationEmail().hashCode()))); pairs.add(new BasicNameValuePair("accessKey",this.config.getSynchronizationAccessKey())); post.setEntity(new UrlEncodedFormEntity(pairs)); HttpResponse response=client.execute(post,this.context); if (response.getStatusLine().getStatusCode() == HTTP_FORBIDDEN) { throw new AccessException(EntityUtils.toString(response.getEntity())); } LOG.debug("Got status " + response.getStatusLine().getStatusCode() + " from server."); } catch ( Exception io) { LOG.error("Got error while POSTing update:",io); } }
Example 85
From project QuotaForAndroid, under directory /Quota/src/com/southfreo/quota/control/.
Source file: ProviderParser.java

private static boolean VirginLogin(DefaultHttpClient http,Provider p){ CacheManager cm=CacheManager.getInstance(); String sLoginUrl="https://www.virginmobile.com.au/selfcare/MyAccount/LogoutLoginPre.jsp"; try { HttpPost post=new HttpPost(sLoginUrl); parameter username_param=p.getParameterByID(1); parameter password_param=p.getParameterByID(3); List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("username",username_param.CurrentValueAsInternalString())); nameValuePairs.add(new BasicNameValuePair("password",password_param.CurrentValueAsInternalString())); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response=http.execute(post); String landing=null; if (response != null) { landing=EntityUtils.toString(response.getEntity()); cm.WriteCachedusageData(p,landing,cm.UsageFile(p),1); if (landing.contains("Welcome to the Members' Area")) { return true; } } } catch ( Exception e) { return false; } return false; }
Example 86
From project Racenet-for-Android, under directory /src/org/racenet/threads/.
Source file: LoginThread.java

@Override public void run(){ HttpClient client=new DefaultHttpClient(); HttpPost post=new HttpPost("http://www.warsow-race.net/tools/remoteauth.php"); Message msg=new Message(); Bundle b=new Bundle(); try { List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("username",this.username)); nameValuePairs.add(new BasicNameValuePair("password",this.password)); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response=client.execute(post); b.putString("xml",InputStreamToString.convert(response.getEntity().getContent())); msg.what=1; } catch ( ClientProtocolException e) { b.putString("exception","ClientProtocolException"); msg.setData(b); msg.what=0; } catch ( IOException e) { b.putString("exception","IOException"); msg.setData(b); msg.what=0; } msg.setData(b); handler.sendMessage(msg); }
Example 87
From project radio-reddit-for-Android, under directory /radioreddit/src/com/radioreddit/android/api/.
Source file: PerformSave.java

@Override protected Void doInBackground(String... params){ final String modhash=params[0]; final String cookie=params[1]; final String id=params[2]; final String type=params[3]; try { final HttpClient httpClient=new DefaultHttpClient(); final HttpPost httpPost=new HttpPost("http://www.reddit.com/api/" + type); final List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("id",id)); nameValuePairs.add(new BasicNameValuePair("uh",modhash)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpPost.setHeader("Cookie","reddit_session=" + cookie); httpClient.execute(httpPost); } catch ( UnsupportedEncodingException e) { Log.i("RedditAPI","UnsupportedEncodingException while performing vote",e); } catch ( ClientProtocolException e) { Log.i("RedditAPI","ClientProtocolException while performing vote",e); } catch ( IOException e) { Log.i("RedditAPI","IOException while performing vote",e); } catch ( ParseException e) { Log.i("RedditAPI","ParseException while performing vote",e); } return null; }
Example 88
From project Rhybudd, under directory /src/net/networksaremadeofstring/rhybudd/.
Source file: ZenossAPIv2.java

public ZenossAPIv2(String UserName,String Password,String URL,String BAUser,String BAPassword) throws Exception { if (URL.contains("https://")) { this.PrepareSSLHTTPClient(); } else { this.PrepareHTTPClient(); } if (!BAUser.equals("") || !BAPassword.equals("")) { CredentialsProvider credProvider=new BasicCredentialsProvider(); credProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST,AuthScope.ANY_PORT),new UsernamePasswordCredentials(BAUser,BAPassword)); httpclient.setCredentialsProvider(credProvider); } HttpParams httpParameters=new BasicHttpParams(); int timeoutConnection=20000; HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection); int timeoutSocket=30000; HttpConnectionParams.setSoTimeout(httpParameters,timeoutSocket); httpclient.setParams(httpParameters); HttpPost httpost=new HttpPost(URL + "/zport/acl_users/cookieAuthHelper/login"); List<NameValuePair> nvps=new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("__ac_name",UserName)); nvps.add(new BasicNameValuePair("__ac_password",Password)); nvps.add(new BasicNameValuePair("submitted","true")); nvps.add(new BasicNameValuePair("came_from",URL + "/zport/dmd")); httpost.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8)); HttpResponse response=httpclient.execute(httpost); response.getEntity().consumeContent(); this.ZENOSS_INSTANCE=URL; this.ZENOSS_USERNAME=UserName; this.ZENOSS_PASSWORD=Password; }
Example 89
From project roman10-android-tutorial, under directory /dash/src/roman10/http/.
Source file: UploadService.java

public int requestFileStatus(String filePath){ int status=0; HttpClient httpclient=new DefaultHttpClient(); try { HttpPost httppost=new HttpPost("http://cervino.ddns.comp.nus.edu.sg/~a0075306/startupload.php"); List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(1); String lFileName=filePath.substring(filePath.lastIndexOf("/") + 1); nameValuePairs.add(new BasicNameValuePair("filename[" + 0 + "]",lFileName)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response=httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { Log.e("queryHttp","Response Status line code:" + response.getStatusLine()); } HttpEntity resEntity=response.getEntity(); if (resEntity == null) { Log.e("queryHttp","No Response!"); } else { BufferedReader br=new BufferedReader(new InputStreamReader(resEntity.getContent())); String line=br.readLine(); Log.i("http reply",line); status=Integer.valueOf(line); br.close(); } } catch ( ClientProtocolException e) { } catch ( IOException e) { } finally { httpclient.getConnectionManager().shutdown(); } return status; }
Example 90
From project rozkladpkp-android, under directory /src/org/tyszecki/rozkladpkp/servers/.
Source file: HafasServer.java

public int getConnections(ArrayList<SerializableNameValuePair> data,String ld){ data=prepareFields(data); DefaultHttpClient client=new DefaultHttpClient(); HttpPost request=new HttpPost(url(URL_CONNECTIONS) + ((ld == null) ? "" : "?ld=" + ld)); client.removeRequestInterceptorByClass(org.apache.http.protocol.RequestExpectContinue.class); client.removeRequestInterceptorByClass(org.apache.http.protocol.RequestUserAgent.class); for (int i=0; i < data.size(); ++i) { Log.i("RozkladPKP",data.get(i).getName() + "=" + data.get(i).getValue()); } request.addHeader("Content-Type","text/plain"); try { request.setEntity(new UrlEncodedFormEntity(data,"UTF-8")); } catch ( UnsupportedEncodingException e) { return DOWNLOAD_ERROR_OTHER; } ByteArrayOutputStream content=new ByteArrayOutputStream(); HttpResponse response; try { response=client.execute(request); HttpEntity entity=response.getEntity(); InputStream inputStream=entity.getContent(); GZIPInputStream in=new GZIPInputStream(inputStream); int readBytes=0; while ((readBytes=in.read(sBuffer)) != -1) { content.write(sBuffer,0,readBytes); } } catch ( Exception e) { return DOWNLOAD_ERROR_SERVER_FAULT; } try { pln=new PLN(content.toByteArray()); } catch ( Exception e) { return DOWNLOAD_ERROR_SERVER_FAULT; } if (ld == null || pln.conCnt > 0) return DOWNLOAD_OK; return DOWNLOAD_ERROR_WAIT; }
Example 91
From project scooter, under directory /source/src/com/scooterframework/common/http/.
Source file: HTTPClient.java

private HttpUriRequest createHttpRequest(String method,String uri,Map<String,String> params) throws UnsupportedEncodingException { List<NameValuePair> nvps=new ArrayList<NameValuePair>(); if (params != null) { for ( Map.Entry<String,String> entry : params.entrySet()) { nvps.add(new BasicNameValuePair(entry.getKey(),entry.getValue())); } } HttpUriRequest request=null; if (GET.equalsIgnoreCase(method)) { request=new HttpGet(uri); } else if (POST.equalsIgnoreCase(method)) { request=new HttpPost(uri); ((HttpPost)request).setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8)); } else if (PUT.equalsIgnoreCase(method)) { request=new HttpPut(uri); ((HttpPut)request).setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8)); } else if (DELETE.equalsIgnoreCase(method)) { request=new HttpDelete(uri); } else if (HEAD.equalsIgnoreCase(method)) { request=new HttpHead(uri); } else if (OPTIONS.equalsIgnoreCase(method)) { request=new HttpOptions(uri); } else { throw new IllegalArgumentException("Method \"" + method + "\" is not supported."); } return request; }
Example 92
/** * Connects to Last.fm servers and requests a Now Playing notification of <code>track</code>. If an error occurs, exceptions are thrown. * @param track the track to send as notification * @throws BadSessionException means that a new handshake is needed * @throws TemporaryFailureException * @throws UnknownResponseException {@link UnknownResponseException} */ public void notifyNowPlaying(Track track,HandshakeResult hInfo) throws BadSessionException, TemporaryFailureException { Log.d(TAG,"Notifying now playing: " + getNetApp().getName()); Log.d(TAG,getNetApp().getName() + ": " + track.toString()); DefaultHttpClient http=new DefaultHttpClient(); HttpPost request=new HttpPost(hInfo.nowPlayingUri); List<BasicNameValuePair> data=new LinkedList<BasicNameValuePair>(); data.add(new BasicNameValuePair("s",hInfo.sessionId)); data.add(new BasicNameValuePair("a",track.getArtist())); data.add(new BasicNameValuePair("b",track.getAlbum())); data.add(new BasicNameValuePair("t",track.getTrack())); data.add(new BasicNameValuePair("l",Integer.toString(track.getDuration()))); data.add(new BasicNameValuePair("n",track.getTrackNr())); data.add(new BasicNameValuePair("m",track.getMbid())); try { request.setEntity(new UrlEncodedFormEntity(data,"UTF-8")); ResponseHandler<String> handler=new BasicResponseHandler(); String response=http.execute(request,handler); if (response.startsWith("OK")) { Log.i(TAG,"Nowplaying success: " + getNetApp().getName()); } else if (response.startsWith("BADSESSION")) { throw new BadSessionException("Nowplaying failed because of badsession"); } else { throw new TemporaryFailureException("NowPlaying failed weirdly: " + response); } } catch ( ClientProtocolException e) { throw new TemporaryFailureException(TAG + ": " + e.getMessage()); } catch ( IOException e) { throw new TemporaryFailureException(TAG + ": " + e.getMessage()); } finally { http.getConnectionManager().shutdown(); } }
Example 93
From project SOCIETIES-SCE-Services, under directory /3rdPartyServices/StudentServices/NearMe/Android/src/com/asocom/tools/.
Source file: Server.java

/** * Start. */ public static void start(){ HttpClient httpclient=new DefaultHttpClient(); HttpPost httppost=new HttpPost(address); try { List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("operation","3")); nameValuePairs.add(new BasicNameValuePair("json","")); nameValuePairs.add(new BasicNameValuePair("ssid",Manager.getSSID())); Log.i("ssid",Manager.getSSID()); Log.i("ssid","" + Manager.getRegisteredUserEmail()); nameValuePairs.add(new BasicNameValuePair("uid",Manager.getRegisteredUserEmail())); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response=httpclient.execute(httppost); String str=inputStreamToString(response.getEntity().getContent()).toString(); initSession(); } catch ( ClientProtocolException e) { } catch ( IOException e) { } timer=new Timer(); timer.scheduleAtFixedRate(new TimerTask(){ public void run(){ Log.i("Server","Server.timer.scheduleAtFixedRate: ---------------------------------- ok ----------------------------------"); try { Json.receiver(Server.getData()); } catch ( Exception e) { } } } ,0,5000); }
Example 94
From project SVQCOM, under directory /Core/src/com/ushahidi/android/app/net/.
Source file: MainHttpClient.java

public static HttpResponse PostURL(String URL,List<NameValuePair> data,String Referer) throws IOException { Preferences.httpRunning=true; try { final HttpPost httpost=new HttpPost(URL); if (Referer.length() > 0) { httpost.addHeader("Referer",Referer); } if (data != null) { try { httpost.getParams().setBooleanParameter("http.protocol.expect-continue",false); httpost.setEntity(new UrlEncodedFormEntity(data,HTTP.UTF_8)); } catch ( final UnsupportedEncodingException e) { e.printStackTrace(); Preferences.httpRunning=false; return null; } } try { HttpResponse response=httpClient.execute(httpost); Preferences.httpRunning=false; return response; } catch ( final Exception e) { } } catch ( final Exception e) { e.printStackTrace(); } Preferences.httpRunning=false; return null; }
Example 95
From project TL-android-app, under directory /tlandroidapp/src/org/opensourcetlapp/tl/.
Source file: TLLib.java

public static void sendPM(String to,String subject,String message) throws IOException { DefaultHttpClient httpclient=new DefaultHttpClient(); httpclient.setCookieStore(cookieStore); HttpPost httpost=new HttpPost(PM_URL); List<NameValuePair> nvps=new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("to",to)); nvps.add(new BasicNameValuePair("subject",subject)); nvps.add(new BasicNameValuePair("body",message)); nvps.add(new BasicNameValuePair("view","Send")); nvps.add(new BasicNameValuePair("token",tokenField)); Log.d(TAG,"Sending message"); Log.d(TAG,to); Log.d(TAG,subject); Log.d(TAG,message); try { httpost.setEntity(new UrlEncodedFormEntity(nvps)); HttpResponse response=httpclient.execute(httpost); HttpEntity entity=response.getEntity(); if (entity != null) { entity.consumeContent(); } } catch ( UnsupportedEncodingException e) { e.printStackTrace(); } catch ( ClientProtocolException e) { e.printStackTrace(); } }
Example 96
From project UDJ-Android-Client, under directory /src/org/klnusbaum/udj/network/.
Source file: ServerConnection.java

public static AuthResult authenticate(String username,String password) throws AuthenticationException, IOException, APIVersionException, JSONException { URI AUTH_URI=null; try { AUTH_URI=new URI(NETWORK_PROTOCOL,null,SERVER_HOST,SERVER_PORT,"/udj/0_6/auth",null,null); } catch ( URISyntaxException e) { } final ArrayList<NameValuePair> params=new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_USERNAME,username)); params.add(new BasicNameValuePair(PARAM_PASSWORD,password)); HttpEntity entity=null; entity=new UrlEncodedFormEntity(params); final HttpPost post=new HttpPost(AUTH_URI); post.addHeader(entity.getContentType()); post.setEntity(entity); final HttpResponse resp=getHttpClient().execute(post); Log.d(TAG,"Auth Status code was " + resp.getStatusLine().getStatusCode()); final String response=EntityUtils.toString(resp.getEntity()); Log.d(TAG,"Auth Response was " + response); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_IMPLEMENTED) { throw new APIVersionException(); } else if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new AuthenticationException(); } else { JSONObject authResponse=new JSONObject(response); return new AuthResult(authResponse.getString("ticket_hash"),authResponse.getString("user_id")); } }
Example 97
From project undertow, under directory /core/src/test/java/io/undertow/test/handlers/form/.
Source file: FormDataParserTestCase.java

private void runTest(final NameValuePair... pairs) throws Exception { DefaultServer.setRootHandler(rootHandler); DefaultHttpClient client=new DefaultHttpClient(); try { final List<NameValuePair> data=new ArrayList<NameValuePair>(); data.addAll(Arrays.asList(pairs)); HttpPost post=new HttpPost(DefaultServer.getDefaultServerAddress() + "/path"); post.setHeader(Headers.CONTENT_TYPE_STRING,FormEncodedDataHandler.APPLICATION_X_WWW_FORM_URLENCODED); post.setEntity(new UrlEncodedFormEntity(data)); HttpResponse result=client.execute(post); Assert.assertEquals(200,result.getStatusLine().getStatusCode()); checkResult(data,result); HttpClientUtils.readResponse(result); } finally { client.getConnectionManager().shutdown(); } }
Example 98
From project Ushahidi_Android, under directory /Core/src/com/ushahidi/android/app/net/.
Source file: MainHttpClient.java

public HttpResponse PostURL(String URL,List<NameValuePair> data,String Referer) throws IOException { if (isConnected()) { try { final HttpPost httpost=new HttpPost(URL); if (Referer.length() > 0) { httpost.addHeader("Referer",Referer); } if (data != null) { try { httpost.getParams().setBooleanParameter("http.protocol.expect-continue",false); httpost.setEntity(new UrlEncodedFormEntity(data,HTTP.UTF_8)); } catch ( final UnsupportedEncodingException e) { e.printStackTrace(); return null; } } try { HttpResponse response=httpClient.execute(httpost); Preferences.httpRunning=false; return response; } catch ( final Exception e) { } } catch ( final Exception e) { e.printStackTrace(); } } return null; }
Example 99
From project WebproxyPortlet, under directory /src/main/java/edu/wisc/my/webproxy/beans/http/.
Source file: HttpManagerImpl.java

public Response doRequest(Request request) throws HttpTimeoutException, IOException { String requestType=request.getType(); int indx=requestType.indexOf('#'); if (indx != -1) { requestType=requestType.substring(0,indx); } final HttpUriRequest method; if (WebproxyConstants.GET_REQUEST.equals(requestType)) { method=new HttpGet(request.getUrl()); } else if (WebproxyConstants.POST_REQUEST.equals(requestType)) { method=new HttpPost(request.getUrl()); final ParameterPair[] postParameters=request.getParameters(); if (postParameters != null) { List<NameValuePair> realParameters=new ArrayList<NameValuePair>(); for (int index=0; index < postParameters.length; index++) { realParameters.add(new BasicNameValuePair(postParameters[index].getName(),postParameters[index].getValue())); } ((HttpPost)method).setEntity(new UrlEncodedFormEntity(realParameters)); } } else if (WebproxyConstants.HEAD_REQUEST.equals(requestType)) { method=new HttpHead(request.getUrl()); } else { throw new IllegalArgumentException("Unknown request type '" + requestType + "'"); } if (request.getHeaders() != null) { IHeader[] headers=request.getHeaders(); for (int index=0; index < headers.length; index++) { method.setHeader(headers[index].getName(),headers[index].getValue()); } } return new ResponseImpl(method,client); }
Example 100
From project YandexAPI, under directory /src/ru/elifantiev/yandex/.
Source file: YandexAPIService.java

protected JSONObject callMethod(String methodName,Map<String,String> params){ Uri.Builder builder=getServiceUri().buildUpon(); builder.scheme("https").appendPath("api").appendPath(methodName); HttpClient client=SSLHttpClientFactory.getNewHttpClient(); HttpPost method=new HttpPost(builder.build().toString()); List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>(params.size()); for ( String param : params.keySet()) { nameValuePairs.add(new BasicNameValuePair(param,params.get(param))); } try { method.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } catch ( UnsupportedEncodingException e) { throw new MethodCallException("Call to " + methodName + " failed",e); } method.setHeader(new BasicHeader("Authorization","Bearer " + token.toString())); try { HttpResponse response=client.execute(method); int statusCode=response.getStatusLine().getStatusCode(); if (statusCode == 200) { return (JSONObject)new JSONTokener(EntityUtils.toString(response.getEntity())).nextValue(); } throw new MethodCallException("Method returned unexpected status code " + String.valueOf(statusCode)); } catch ( IOException e) { throw new MethodCallException("Call to " + methodName + " failed",e); } catch ( JSONException e) { throw new FormatException("Call to " + methodName + " failed due to wrong response format",e); } }