Java Code Examples for org.apache.http.client.methods.HttpPost

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 ALP, under directory /workspace/alp-reporter/src/main/java/com/lohika/alp/reporter/client/.

Source file: LogUploader.java

  35 
vote

/** 
 * Upload certain log to server.
 * @param testMethodId the ID of test method which log will be uploaded 
 * @param logFile - instance of file to upload 
 * @throws ClientProtocolException the client protocol exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void upload(long testMethodId,File logFile) throws ClientProtocolException, IOException {
  String url=server + "/results/test-method/" + testMethodId+ "/log";
  HttpClient httpclient=new DefaultHttpClient();
  HttpPost httppost=new HttpPost(url);
  MultipartEntity mpEntity=new MultipartEntity();
  ContentBody cbFile=new FileBody(logFile);
  mpEntity.addPart("fileData",cbFile);
  httppost.setEntity(mpEntity);
  httpclient.execute(httppost);
}
 

Example 2

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

Source file: GAEConnector.java

  32 
vote

/** 
 */
public int POSTContentBody(String relativeUrl,String body,boolean authenticated,boolean disableRedirect) throws Exception {
  DefaultHttpClient httpClient=this.CreateHttpClient(disableRedirect);
  HttpPost httpPost=new HttpPost(_gaeAppBaseUrl + relativeUrl);
  this.SetHttpRequestAuthCookie(httpPost,authenticated);
  ByteArrayEntity entity=new ByteArrayEntity(body.getBytes("UTF-8"));
  httpPost.setEntity(entity);
  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 3

From project android-rackspacecloud, under directory /main/java/net/elasticgrid/rackspace/cloudservers/.

Source file: XMLCloudServers.java

  32 
vote

public void rebootServer(int serverID,RebootType type) throws CloudServersException {
  logger.log(Level.INFO,"Rebooting server {0} via {1} reboot...",new Object[]{serverID,type.name()});
  validateServerID(serverID);
  HttpPost request=new HttpPost(getServerManagementURL() + "/servers/" + serverID+ "/action");
  Reboot reboot=new Reboot();
  reboot.setType(net.elasticgrid.rackspace.cloudservers.internal.RebootType.valueOf(type.name()));
  makeEntityRequestInt(request,reboot);
}
 

Example 4

From project android_7, under directory /src/org/immopoly/android/helper/.

Source file: WebHelper.java

  32 
vote

private static HttpResponse postHttp(String url,JSONObject jsonObject) throws ClientProtocolException, IOException {
  HttpClient httpclient=new DefaultHttpClient();
  HttpPost httppost=new HttpPost(url);
  httppost.setHeader("User-Agent","immopoly android client " + ImmopolyActivity.getStaticVersionInfo());
  httppost.setHeader("Accept-Encoding","gzip");
  HttpEntity entity;
  entity=new StringEntity(jsonObject.toString());
  httppost.setEntity(entity);
  return httpclient.execute(httppost);
}
 

Example 5

From project android_packages_apps_Gallery3D, under directory /src/com/cooliris/picasa/.

Source file: GDataClient.java

  32 
vote

public void post(String feedUrl,byte[] data,String contentType,Operation operation) throws IOException {
  ByteArrayEntity entity=getCompressedEntity(data);
  entity.setContentType(contentType);
  HttpPost post=new HttpPost(feedUrl);
  post.setEntity(entity);
  callMethod(post,operation);
}
 

Example 6

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

Source file: PostReporter.java

  32 
vote

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

Example 7

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

Source file: ConnectionOAuth.java

  32 
vote

@Override public JSONObject createFavorite(String statusId) throws ConnectionException {
  StringBuilder url=new StringBuilder(getApiUrl(apiEnum.FAVORITES_CREATE_BASE));
  url.append(statusId);
  url.append(EXTENSION);
  HttpPost post=new HttpPost(url.toString());
  return postRequest(post);
}
 

Example 8

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

Source file: ConnectionOAuth.java

  32 
vote

@Override public JSONObject createFavorite(long statusId) throws ConnectionException {
  StringBuilder url=new StringBuilder(FAVORITES_CREATE_BASE_URL);
  url.append(String.valueOf(statusId));
  url.append(EXTENSION);
  HttpPost post=new HttpPost(url.toString());
  return postRequest(post);
}
 

Example 9

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

Source file: FileApiClientAdapterImpl.java

  32 
vote

public ApiResponse<UploadData> uploadFile(FileType fileType,String fileUri,File fileToUpload,Boolean approveContent,String fileEncoding,String callbackUrl) throws FileApiException {
  String params=buildParamsQuery(new BasicNameValuePair(FILE_URI,fileUri),new BasicNameValuePair(FILE_TYPE,fileType.getIdentifier()),new BasicNameValuePair(APPROVED,null == approveContent ? null : Boolean.toString(approveContent)),new BasicNameValuePair(CALLBACK_URL,callbackUrl));
  HttpPost httpPostFile=createFileUploadHttpPostRequest(params,fileToUpload,fileEncoding);
  StringResponse response=executeHttpcall(httpPostFile);
  return getApiResponse(response.getContents(),new TypeToken<ApiResponseWrapper<UploadData>>(){
  }
.getType());
}
 

Example 10

From project Axon-trader, under directory /external-listeners/src/main/java/org/axonframework/samples/trader/listener/.

Source file: OrderbookExternalListener.java

  32 
vote

private void doHandle(TradeExecutedEvent event) throws IOException {
  String jsonObjectAsString=createJsonInString(event);
  HttpPost post=new HttpPost(remoteServerUri);
  post.setEntity(new StringEntity(jsonObjectAsString));
  post.addHeader("Content-Type","application/json");
  HttpClient client=new DefaultHttpClient();
  HttpResponse response=client.execute(post);
  if (response.getStatusLine().getStatusCode() != 200) {
    Writer writer=new StringWriter();
    IOUtils.copy(response.getEntity().getContent(),writer);
    logger.warn("Error while sending event to external system: {}",writer.toString());
  }
}
 

Example 11

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

Source file: AuthUserApiHandler.java

  32 
vote

/** 
 * Call the API.
 * @return		Resulting User ID, 0 if error/none.
 */
public long getAuthUser(){
  HttpPost post=new HttpPost("http://www.goodreads.com/api/auth_user");
  mUserId=0;
  try {
    XmlResponseParser handler=new XmlResponseParser(mRootFilter);
    mManager.execute(post,handler,true);
    return mUserId;
  }
 catch (  Exception e) {
    return 0;
  }
}
 

Example 12

From project build-info, under directory /build-info-client/src/main/java/org/jfrog/build/client/.

Source file: ArtifactoryBuildInfoClient.java

  32 
vote

public HttpResponse executeUserPlugin(String executionName,Map<String,String> requestParams) throws IOException {
  StringBuilder urlBuilder=new StringBuilder(artifactoryUrl).append("/api/plugins/execute/").append(executionName).append("?");
  appendParamsToUrl(requestParams,urlBuilder);
  HttpPost postRequest=new HttpPost(urlBuilder.toString());
  return httpClient.getHttpClient().execute(postRequest);
}
 

Example 13

From project couchdb-lucene, under directory /src/main/java/com/github/rnewson/couchdb/lucene/couchdb/.

Source file: HttpUtils.java

  32 
vote

public static final String post(final HttpClient httpClient,final String url,final JSONObject body) throws IOException {
  final HttpPost post=new HttpPost(url);
  post.setHeader("Content-Type",Constants.APPLICATION_JSON);
  post.setEntity(new StringEntity(body.toString(),"UTF-8"));
  return execute(httpClient,post);
}
 

Example 14

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

Source file: NetworkHelper.java

  32 
vote

public String doHTTPPost(String uri){
  String response=null;
  HttpPost hTTPPost=new HttpPost(uri);
  try {
    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 15

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

Source file: CloudClient.java

  32 
vote

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 16

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

Source file: HttpUtils.java

  32 
vote

/** 
 * A simple POST Http call to the url
 * @param url
 * @param jsonContent
 * @return 
 * @throws ClientProtocolException
 * @throws IOException
 */
public static String doPostJson(String url,String jsonContent) throws ClientProtocolException, IOException {
  ResponseHandler<String> responseHandler=new BasicResponseHandler();
  DefaultHttpClient httpProxyClient=new DefaultHttpClient();
  HttpHost proxy=new HttpHost("localhost",EasySOAConstants.HTTP_DISCOVERY_PROXY_PORT);
  httpProxyClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
  HttpPost httpPost=new HttpPost(url);
  httpPost.setHeader("Content-Type","application/json; charset=UTF-8");
  httpPost.setEntity(new StringEntity(jsonContent));
  return httpProxyClient.execute(httpPost,responseHandler);
}
 

Example 17

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

Source file: OAuth.java

  32 
vote

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 18

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

Source file: HttpClientHelper.java

  32 
vote

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

Example 19

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

Source file: HQConnection.java

  32 
vote

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

Example 20

From project httpClient, under directory /httpclient/src/test/java/org/apache/http/impl/client/.

Source file: TestDecompressingHttpClient.java

  32 
vote

@Test public void passesThroughTheBodyOfAPOST() throws Exception {
  when(mockHandler.handleResponse(isA(HttpResponse.class))).thenReturn(new Object());
  HttpPost post=new HttpPost("http://localhost:8080/");
  post.setEntity(new ByteArrayEntity("hello".getBytes()));
  impl.execute(host,post,mockHandler,ctx);
  assertNotNull(((HttpEntityEnclosingRequest)backend.getCapturedRequest()).getEntity());
}
 

Example 21

From project javaee-tutorial, under directory /jaxrs/android/src/org/jboss/ee/tutorial/jaxrs/android/data/.

Source file: LibraryHttpClient.java

  32 
vote

private String post(String path,String title){
  try {
    HttpPost request=new HttpPost(getRequestURI(path));
    request.setHeader("Content-Type","application/json");
    request.setEntity(new StringEntity(title));
    HttpResponse res=httpClient.execute(request);
    String content=EntityUtils.toString(res.getEntity());
    return content;
  }
 catch (  Exception ex) {
    ex.printStackTrace();
    return null;
  }
}
 

Example 22

From project jdeltasync, under directory /src/main/java/com/googlecode/jdeltasync/.

Source file: DeltaSyncClient.java

  32 
vote

private HttpPost createHttpPost(String uri,String userAgent,String contentType,byte[] data){
  ByteArrayEntity entity=new ByteArrayEntity(data);
  entity.setContentType(contentType);
  HttpPost post=new HttpPost(uri);
  post.setHeader("User-Agent",userAgent);
  post.setEntity(entity);
  return post;
}
 

Example 23

From project jetty-project, under directory /jetty-reverse-http/reverse-http-client/src/main/java/org/mortbay/jetty/rhttp/client/.

Source file: ApacheClient.java

  32 
vote

protected void syncHandshake() throws IOException {
  HttpPost handshake=new HttpPost(gatewayPath + "/" + urlEncode(getTargetId())+ "/handshake");
  HttpResponse response=httpClient.execute(handshake);
  int statusCode=response.getStatusLine().getStatusCode();
  HttpEntity entity=response.getEntity();
  if (entity != null)   entity.consumeContent();
  if (statusCode != HttpStatus.SC_OK)   throw new IOException("Handshake failed");
  getLogger().debug("Client {} handshake returned from gateway",getTargetId(),null);
}
 

Example 24

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

Source file: HttpPoster.java

  31 
vote

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

Example 25

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

Source file: SIAC.java

  31 
vote

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

Example 26

From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/util/http/.

Source file: HttpBuilder.java

  31 
vote

private <T>HttpResult<T> doPost(Type target){
  try {
    URI path=createPath(address);
    HttpPost post=new HttpPost(path);
    HttpEntity entity=prepareMultipart();
    post.setEntity(entity);
    return doRequest(post,target);
  }
 catch (  UnsupportedEncodingException e) {
    Log.e(Constants.TAG,"Couldn't process parameters",e);
    return error();
  }
catch (  URISyntaxException e) {
    Log.e(Constants.TAG,"Couldn't create path",e);
    return error();
  }
}
 

Example 27

From project Alerte-voirie-android, under directory /src/com/fabernovel/alertevoirie/webservice/.

Source file: AVService.java

  31 
vote

@Override protected HttpResponse[] doInBackground(ArrayList<Object>... params){
  HttpResponse[] response=new HttpResponse[2];
  int i=0;
  for (  ArrayList<Object> PicArray : params) {
    if (PicArray != null) {
      HttpClient httpClient=new DefaultHttpClient();
      HttpContext localContext=new BasicHttpContext();
      HttpPost httpPost=new HttpPost((String)PicArray.get(0));
      httpPost.addHeader("udid",(String)PicArray.get(1));
      Log.d(Constants.PROJECT_TAG,"length : " + ((String)PicArray.get(2)).length());
      httpPost.addHeader("img_comment",(String)PicArray.get(2));
      httpPost.addHeader("incident_id",(String)PicArray.get(3));
      httpPost.addHeader("type",(String)PicArray.get(4));
      if (((Boolean)PicArray.get(6)).booleanValue()) {
        httpPost.addHeader("INCIDENT_CREATION","true");
      }
      try {
        FileEntity file=new FileEntity((File)PicArray.get(5),"image/jpeg");
        file.setContentType("image/jpeg");
        httpPost.setEntity(file);
        response[i++]=httpClient.execute(httpPost,localContext);
      }
 catch (      IOException e) {
        Log.e(Constants.PROJECT_TAG,"IOException postImage",e);
      }
catch (      IllegalStateException e) {
        Log.e(Constants.PROJECT_TAG,"IllegalStateException postImage",e);
      }
    }
  }
  return response;
}
 

Example 28

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

Source file: AsyncHttpClient.java

  31 
vote

/** 
 * Perform a HTTP POST request and track the Android Context which initiated the request. Set headers only for this request
 * @param context the Android Context which initiated the request.
 * @param url the URL to send the request to.
 * @param headers set headers only for this request
 * @param params additional POST parameters to send with the request.
 * @param contentType the content type of the payload you are sending, forexample application/json if sending a json payload.
 * @param responseHandler the response handler instance that should handlethe response.
 */
public void post(Context context,String url,Header[] headers,RequestParams params,String contentType,AsyncHttpResponseHandler responseHandler){
  HttpEntityEnclosingRequestBase request=new HttpPost(url);
  if (params != null)   request.setEntity(paramsToEntity(params));
  if (headers != null)   request.setHeaders(headers);
  sendRequest(httpClient,httpContext,request,contentType,responseHandler,context);
}
 

Example 29

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

Source file: Rikslunchen.java

  31 
vote

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

From project android-client, under directory /xwiki-android-rest/src/org/xwiki/android/rest/.

Source file: HttpConnector.java

  31 
vote

/** 
 * Perform HTTP Post method execution and return its Response
 * @param uri URL of XWiki RESTful API call.
 * @param content content to be posted to the server
 * @return status code of the Post method execution
 * @throws RestConnectionException
 * @throws RestException
 */
HttpResponse post(String uri,String content) throws RestConnectionException, RestException {
  initialize();
  setCredentials();
  HttpPost request=new HttpPost();
  try {
    URI requestUri=new URI(uri);
    request.setURI(requestUri);
  }
 catch (  URISyntaxException e) {
    e.printStackTrace();
  }
  Log.d(TAG,"POST URL :" + uri);
  try {
    Log.d("Post content","content=" + content);
    StringEntity se=new StringEntity(content,"UTF-8");
    se.setContentType("application/xml");
    request.setEntity(se);
    request.setHeader("Content-Type","application/xml;charset=UTF-8");
    HttpResponse response=client.execute(request);
    Log.d(TAG,response.getStatusLine().toString());
    validate(response.getStatusLine().getStatusCode());
    return response;
  }
 catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    throw new RestConnectionException(e);
  }
  return null;
}
 

Example 31

From project android-shuffle, under directory /client/src/org/dodgybits/shuffle/android/synchronisation/tracks/.

Source file: WebClient.java

  31 
vote

protected synchronized String postContentToUrl(String url,String content) throws ApiException {
  if (sUserAgent == null) {
    throw new ApiException("User-Agent string must be prepared");
  }
  HttpClient client=CreateClient();
  java.net.URI uri=URI.create(url);
  HttpHost host=GetHost(uri);
  HttpPost request=new HttpPost(uri.getPath());
  request.setHeader("User-Agent",sUserAgent);
  request.setHeader("Content-Type","text/xml");
  HttpEntity ent;
  try {
    ent=new StringEntity(content,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
    throw new ApiException("unsupported encoding set",e);
  }
  request.setEntity(ent);
  try {
    HttpResponse response=client.execute(host,request);
    StatusLine status=response.getStatusLine();
    Log.i(cTag,"post with response " + status.toString());
    if (status.getStatusCode() != HttpStatus.SC_CREATED) {
      throw new ApiException("Invalid response from server: " + status.toString() + " for content: "+ content);
    }
    Header[] header=response.getHeaders("Location");
    if (header.length != 0)     return header[0].getValue();
 else     return null;
  }
 catch (  IOException e) {
    throw new ApiException("Problem communicating with API",e);
  }
}
 

Example 32

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

Source file: NetworkUtilities.java

  31 
vote

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

Example 33

From project android_packages_apps_Exchange, under directory /src/com/android/exchange/.

Source file: EasSyncService.java

  31 
vote

public EasResponse sendHttpClientPost(String cmd,HttpEntity entity,int timeout) throws IOException {
  HttpClient client=getHttpClient(timeout);
  boolean isPingCommand=cmd.equals(PING_COMMAND);
  String extra=null;
  boolean msg=false;
  if (cmd.startsWith("SmartForward&") || cmd.startsWith("SmartReply&")) {
    int cmdLength=cmd.indexOf('&');
    extra=cmd.substring(cmdLength);
    cmd=cmd.substring(0,cmdLength);
    msg=true;
  }
 else   if (cmd.startsWith("SendMail&")) {
    msg=true;
  }
  String us=makeUriString(cmd,extra);
  HttpPost method=new HttpPost(URI.create(us));
  if (msg && (mProtocolVersionDouble < Eas.SUPPORTED_PROTOCOL_EX2010_DOUBLE)) {
    method.setHeader("Content-Type","message/rfc822");
  }
 else   if (entity != null) {
    method.setHeader("Content-Type","application/vnd.ms-sync.wbxml");
  }
  setHeaders(method,!isPingCommand);
  if (isPingCommand) {
    method.setHeader("Connection","close");
  }
  method.setEntity(entity);
  return executePostWithTimeout(client,method,timeout,isPingCommand);
}
 

Example 34

From project Anki-Android, under directory /src/com/ichi2/anki/.

Source file: AnkiDroidProxy.java

  31 
vote

public String getDecks(){
  String decksServer="{}";
  try {
    String data="p=" + URLEncoder.encode(mPassword,"UTF-8") + "&client=ankidroid-0.4&u="+ URLEncoder.encode(mUsername,"UTF-8")+ "&d=None&sources="+ URLEncoder.encode("[]","UTF-8")+ "&libanki=0.9.9.8.6&pversion=5";
    HttpPost httpPost=new HttpPost(SYNC_URL + "getDecks");
    StringEntity entity=new StringEntity(data);
    httpPost.setEntity(entity);
    httpPost.setHeader("Accept-Encoding","identity");
    httpPost.setHeader("Content-type","application/x-www-form-urlencoded");
    DefaultHttpClient httpClient=new DefaultHttpClient();
    HttpResponse response=httpClient.execute(httpPost);
    Log.i(AnkiDroidApp.TAG,"Response = " + response.toString());
    HttpEntity entityResponse=response.getEntity();
    Log.i(AnkiDroidApp.TAG,"Entity's response = " + entityResponse.toString());
    InputStream content=entityResponse.getContent();
    Log.i(AnkiDroidApp.TAG,"Content = " + content.toString());
    decksServer=Utils.convertStreamToString(new InflaterInputStream(content));
    Log.i(AnkiDroidApp.TAG,"String content = " + decksServer);
  }
 catch (  UnsupportedEncodingException e) {
    e.printStackTrace();
  }
catch (  ClientProtocolException e) {
    Log.i(AnkiDroidApp.TAG,"ClientProtocolException = " + e.getMessage());
  }
catch (  IOException e) {
    Log.i(AnkiDroidApp.TAG,"IOException = " + e.getMessage());
  }
  return decksServer;
}
 

Example 35

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

Source file: AbstractIntegrationTest.java

  31 
vote

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

Example 36

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

Source file: ACSAuthenticationHelper.java

  31 
vote

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

Example 37

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

Source file: HttpSupport.java

  31 
vote

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

Example 38

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

Source file: Authentication.java

  31 
vote

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

Example 39

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

Source file: RequestHandler.java

  31 
vote

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

Example 40

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

Source file: BackgroundSharingService.java

  31 
vote

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

Example 41

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

Source file: OCTranspoDataFetcher.java

  31 
vote

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

Example 42

From project capedwarf-green, under directory /connect/src/main/java/org/jboss/capedwarf/connect/server/.

Source file: ServerProxyHandler.java

  31 
vote

/** 
 * Get content as a input stream.
 * @param qi     the additional client query info
 * @param entity the http entity
 * @return the response input stream
 * @throws Throwable for any error
 */
protected Result getResultWithHttpEntity(QueryInfo qi,HttpEntity entity) throws Throwable {
  String link=config.getEndpoint(qi.secure) + qi.query;
  if (config.isDebugLogging())   getEnv().log(Constants.TAG_CONNECTION,Level.INFO,"URL: " + link,null);
  HttpPost httppost=new HttpPost(link);
  if (entity != null)   httppost.setEntity(entity);
  for (  Header header : HttpHeaders.getHeaders()) {
    httppost.addHeader(header);
  }
  if (qi.secure) {
    Environment env=EnvironmentFactory.getEnvironment();
    long id=env.getUserId();
    String token=env.getUserToken();
    httppost.addHeader(Constants.CLIENT_ID,String.valueOf(id));
    httppost.addHeader(Constants.CLIENT_TOKEN,token);
  }
  if (GzipOptionalSerializator.isGzipEnabled()) {
    httppost.addHeader(Constants.CONTENT_ENCODING,Constants.GZIP);
  }
  Result result=new Result();
  try {
    HttpResponse response=getClient().execute(httppost);
    result.status=response.getStatusLine().getStatusCode();
    Header h=response.getFirstHeader("Content-Length");
    if (h != null)     result.contentLength=Long.parseLong(h.getValue());
    result.stream=response.getEntity().getContent();
  }
  finally {
    result.end();
  }
  return result;
}
 

Example 43

From project chargifyService, under directory /src/main/java/com/mondora/chargify/controller/.

Source file: Chargify.java

  31 
vote

public MeteredUsage componentCreateUsage(String sub,String comp,Integer quantity,String memo) throws ChargifyException {
  String xml="<usage>" + "<id>" + AUTO_GENERATED + "</id>"+ "<quantity type=\"integer\">"+ Integer.toString(quantity)+ "</quantity>"+ "<memo>"+ String.valueOf(memo)+ "</memo>"+ "</usage>";
  HttpPost method=new HttpPost("/subscriptions/" + sub + "/components/"+ comp+ "/usages.xml");
  try {
    StringEntity entity=new StringEntity(xml);
    entity.setContentEncoding(charset);
    entity.setContentType(contentType);
    method.setEntity(entity);
    HttpResponse response=executeHttpMethod(method);
    handleResponseCode(response,method);
    return (MeteredUsage)parse(MeteredUsage.class,response,method);
  }
 catch (  Exception e) {
    throw new ChargifyException(e);
  }
}
 

Example 44

From project CheckIn4Me, under directory /src/com/davidivins/checkin4me/oauth/.

Source file: OAuth2Request.java

  31 
vote

/** 
 * execute
 * @return Response from executing the request
 */
@Override public Response execute(){
  BufferedReader page=null;
  OAuthResponse response=new OAuthResponse();
  Log.i(TAG,"executing OAuth 2.0 request...");
  String url_string=generateURL();
  Log.i(TAG,"request url = " + url_string);
  try {
    HttpClient httpclient=getTolerantClient();
    HttpResponse http_response;
    if (method.equals("GET")) {
      HttpGet httpget=new HttpGet(url_string);
      http_response=httpclient.execute(httpget);
    }
 else {
      HttpPost httppost=new HttpPost(url_string);
      http_response=httpclient.execute(httppost);
    }
    page=new BufferedReader(new InputStreamReader(http_response.getEntity().getContent(),RESPONSE_ENCODING));
    String line;
    while ((line=page.readLine()) != null) {
      Log.i(TAG,"line = " + line);
      response.appendResponseString(line);
    }
    response.setSuccessStatus(true);
  }
 catch (  IOException e) {
    response.set(false,e.getMessage());
    Log.e(TAG,"EXCEPTION: " + e.getMessage());
  }
  Log.i(TAG,"response.getSuccessStatus = " + response.getSuccessStatus());
  Log.i(TAG,"response.getResponseString = " + response.getResponseString());
  return response;
}
 

Example 45

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

Source file: RESTHelper.java

  31 
vote

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

Example 46

From project cloudify, under directory /rest-client/src/main/java/org/cloudifysource/restclient/.

Source file: GSRestClient.java

  31 
vote

/** 
 * This methods executes HTTP post over REST on the given (relative) URL with the given parameters map.
 * @param relativeUrl The URL to post to.
 * @param params      parameters as Map<String, String>.
 * @return The response object from the REST server
 * @throws RestException Reporting failure to post the file.
 */
public final Object post(final String relativeUrl,final Map<String,String> params) throws RestException {
  final HttpPost httppost=new HttpPost(getFullUrl(relativeUrl));
  if (params != null) {
    HttpEntity entity;
    try {
      final String json=GSRestClient.mapToJson(params);
      entity=new StringEntity(json,MIME_TYPE_APP_JSON,"UTF-8");
      httppost.setEntity(entity);
      httppost.setHeader(HttpHeaders.CONTENT_TYPE,MIME_TYPE_APP_JSON);
    }
 catch (    final IOException e) {
      throw new RestException(e);
    }
  }
  return executeHttpMethod(httppost);
}
 

Example 47

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

Source file: Session.java

  31 
vote

/** 
 * Send a POST with a body and query string
 * @param url
 * @param content
 * @param queryString
 * @return
 */
CouchResponse post(String url,String content,String queryString){
  HttpPost post=new HttpPost(buildUrl(url,queryString));
  if (content != null) {
    HttpEntity entity;
    try {
      entity=new StringEntity(content,DEFAULT_CHARSET);
      post.setEntity(entity);
      post.setHeader(new BasicHeader("Content-Type",MIME_TYPE_JSON));
    }
 catch (    UnsupportedEncodingException e) {
      log.error(ExceptionUtils.getStackTrace(e));
    }
  }
  return http(post);
}
 

Example 48

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

Source file: JSONParser.java

  31 
vote

public JSONObject getJSONFromUrl(String url,List<NameValuePair> params){
  try {
    DefaultHttpClient httpClient=new DefaultHttpClient();
    HttpPost httpPost=new HttpPost(url);
    httpPost.setEntity(new UrlEncodedFormEntity(params));
    HttpResponse httpResponse=httpClient.execute(httpPost);
    HttpEntity httpEntity=httpResponse.getEntity();
    is=httpEntity.getContent();
  }
 catch (  UnsupportedEncodingException e) {
    e.printStackTrace();
  }
catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
  try {
    BufferedReader reader=new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
    StringBuilder sb=new StringBuilder();
    String line=null;
    while ((line=reader.readLine()) != null) {
      sb.append(line + "n");
    }
    is.close();
    json=sb.toString();
    Log.e("JSON",json);
  }
 catch (  Exception e) {
    Log.e("Buffer Error","Error converting result " + e.toString());
  }
  try {
    jObj=new JSONObject(json);
  }
 catch (  JSONException e) {
    Log.e("JSON Parser","Error parsing data " + e.toString());
  }
  return jObj;
}
 

Example 49

From project CyborgFactoids, under directory /src/main/java/com/alta189/cyborg/factoids/util/.

Source file: HTTPUtil.java

  31 
vote

public static String hastebin(String data){
  HttpClient client=new DefaultHttpClient();
  HttpPost post=new HttpPost(hastebin);
  try {
    post.setEntity(new StringEntity(data));
    HttpResponse response=client.execute(post);
    String result=EntityUtils.toString(response.getEntity());
    return "http://hastebin.com/" + new Gson().fromJson(result,Hastebin.class).getKey();
  }
 catch (  UnsupportedEncodingException e) {
    e.printStackTrace();
  }
catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 50

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

Source file: Helper.java

  31 
vote

static void sendLog(Intent intent){
  final String registrationId=intent.getStringExtra("registration_id");
  if (registrationId == null)   return;
  new Thread(){
    public void run(){
      AndroidHttpClient client=AndroidHttpClient.newInstance("LogPush");
      try {
        ArrayList<String> commandLine=new ArrayList<String>();
        commandLine.add("logcat");
        commandLine.add("-d");
        Process process=Runtime.getRuntime().exec(commandLine.toArray(new String[0]));
        byte[] data=StreamUtility.readToEndAsArray(process.getInputStream());
        HttpPost post=new HttpPost("http://logpush.clockworkmod.com/" + registrationId);
        post.setEntity(new ByteArrayEntity(data));
        post.setHeader("Content-Type","application/binary");
        HttpResponse resp=client.execute(post);
        String contents=StreamUtility.readToEnd(resp.getEntity().getContent());
        Log.i("LogPush",contents);
      }
 catch (      Exception e) {
        e.printStackTrace();
      }
 finally {
        client.close();
      }
    }
  }
.start();
}
 

Example 51

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

Source file: RateDigitbooksActivity.java

  31 
vote

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

Example 52

From project DrmLicenseService, under directory /src/com/sonyericsson/android/drm/drmlicenseservice/.

Source file: HttpClient.java

  31 
vote

public static Response post(Context context,long sessionId,String url,String messageType,String data,Bundle parameters,DataHandlerCallback callback,RetryCallback retryCallback){
  Response response=null;
  final String fUrl=url;
  final String fMessageType=messageType;
  final String fData=data;
  final Bundle fParameters=parameters;
  response=runAsThread(context,sessionId,parameters,retryCallback,new HttpThread.HttpThreadAction(callback){
    public HttpRequestBase getRequest(){
      HttpPost request=null;
      if (fUrl != null && fUrl.length() > 0) {
        try {
          request=new HttpPost(fUrl);
        }
 catch (        IllegalArgumentException e) {
          return null;
        }
        request.setHeader("Content-Type","text/xml; charset=utf-8");
        addParameters(fParameters,request);
        if (fMessageType != null && fMessageType.length() > 0) {
          request.setHeader("SOAPAction","\"http://schemas.microsoft.com/DRM/2007/03/protocols/" + fMessageType + "\"");
        }
        if (fData != null && fData.length() > 0) {
          ByteArrayBuffer bab=new ByteArrayBuffer(fData.length());
          bab.append(fData.getBytes(),0,fData.length());
          writeDataToFile("post",bab);
          try {
            request.setEntity(new StringEntity(fData));
          }
 catch (          UnsupportedEncodingException e) {
          }
        }
      }
      return request;
    }
  }
);
  return response;
}
 

Example 53

From project droidparts, under directory /extra/src/org/droidparts/http/.

Source file: RESTClient.java

  31 
vote

public String post(String uri,String contentEncoding,String data) throws HTTPException {
  L.d("POST on " + uri + ", data: "+ data);
  HttpPost req=new HttpPost(uri);
  try {
    StringEntity entity=new StringEntity(data,UTF8);
    entity.setContentType(contentEncoding);
    req.setEntity(entity);
  }
 catch (  UnsupportedEncodingException e) {
    L.e(e);
    throw new HTTPException(e);
  }
  DefaultHttpClientWrapper wrapper=getLegacy();
  HttpResponse resp=wrapper.getResponse(req);
  String respStr=DefaultHttpClientWrapper.getResponseBody(resp);
  DefaultHttpClientWrapper.consumeResponse(resp);
  return respStr;
}
 

Example 54

From project DTE, under directory /src/cl/nic/dte/net/.

Source file: ConexionSii.java

  31 
vote

private RECEPCIONDTEDocument uploadEnvio(String rutEnvia,String rutCompania,File archivoEnviarSII,String token,String urlEnvio,String hostEnvio) throws ClientProtocolException, IOException, org.apache.http.ParseException, XmlException {
  HttpClient httpclient=new DefaultHttpClient();
  HttpPost httppost=new HttpPost(urlEnvio);
  MultipartEntity reqEntity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
  reqEntity.addPart("rutSender",new StringBody(rutEnvia.substring(0,rutEnvia.length() - 2)));
  reqEntity.addPart("dvSender",new StringBody(rutEnvia.substring(rutEnvia.length() - 1,rutEnvia.length())));
  reqEntity.addPart("rutCompany",new StringBody(rutCompania.substring(0,(rutCompania).length() - 2)));
  reqEntity.addPart("dvCompany",new StringBody(rutCompania.substring(rutCompania.length() - 1,rutCompania.length())));
  FileBody bin=new FileBody(archivoEnviarSII);
  reqEntity.addPart("archivo",bin);
  httppost.setEntity(reqEntity);
  BasicClientCookie cookie=new BasicClientCookie("TOKEN",token);
  cookie.setPath("/");
  cookie.setDomain(hostEnvio);
  cookie.setSecure(true);
  cookie.setVersion(1);
  CookieStore cookieStore=new BasicCookieStore();
  cookieStore.addCookie(cookie);
  httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.RFC_2109);
  httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.BROWSER_COMPATIBILITY);
  HttpContext localContext=new BasicHttpContext();
  localContext.setAttribute(ClientContext.COOKIE_STORE,cookieStore);
  httppost.addHeader(new BasicHeader("User-Agent",Utilities.netLabels.getString("UPLOAD_SII_HEADER_VALUE")));
  HttpResponse response=httpclient.execute(httppost,localContext);
  HttpEntity resEntity=response.getEntity();
  RECEPCIONDTEDocument resp=null;
  HashMap<String,String> namespaces=new HashMap<String,String>();
  namespaces.put("","http://www.sii.cl/SiiDte");
  XmlOptions opts=new XmlOptions();
  opts.setLoadSubstituteNamespaces(namespaces);
  resp=RECEPCIONDTEDocument.Factory.parse(EntityUtils.toString(resEntity),opts);
  return resp;
}
 

Example 55

From project dungbeetle, under directory /src/edu/stanford/mobisocial/dungbeetle/google/.

Source file: OAuthFlowApp.java

  31 
vote

private String doPost(String url,String payload,String contentType,OAuthConsumer consumer) throws Exception {
  DefaultHttpClient client=new DefaultHttpClient();
  HttpPost request=new HttpPost(url);
  StringEntity se=new StringEntity(payload,HTTP.UTF_8);
  se.setContentType(contentType);
  request.setEntity(se);
  consumer.sign(request);
  StringBuffer sb=new StringBuffer();
  try {
    HttpResponse execute=client.execute(request);
    InputStream content=execute.getEntity().getContent();
    BufferedReader buffer=new BufferedReader(new InputStreamReader(content));
    String s="";
    while ((s=buffer.readLine()) != null) {
      sb.append(s);
    }
    return sb.toString();
  }
 catch (  Exception e) {
    e.printStackTrace();
    return null;
  }
}
 

Example 56

From project emite, under directory /src/test/java/com/calclab/emite/xtesting/services/.

Source file: HttpConnector.java

  31 
vote

private Runnable createSendAction(final String httpBase,final String xml,final ConnectorCallback callback){
  return new Runnable(){
    @Override public void run(){
      final String id=HttpConnectorID.getNext();
      debug("Connector [{0}] send: {1}",id,xml);
      final HttpClient client=new DefaultHttpClient();
      int status=0;
      String responseString=null;
      final HttpPost post=new HttpPost(httpBase);
      try {
        post.setEntity(new StringEntity(xml,"utf-8"));
        System.out.println("SENDING: " + xml);
        final HttpResponse response=client.execute(post);
        responseString=EntityUtils.toString(response.getEntity());
      }
 catch (      final Exception e) {
        callback.onResponseError(xml,e);
        e.printStackTrace();
      }
      try {
        post.setEntity(new StringEntity(xml,"text/xml"));
        System.out.println("SENDING: " + xml);
        HttpResponse response=client.execute(post);
        responseString=EntityUtils.toString(response.getEntity());
        status=response.getStatusLine().getStatusCode();
      }
 catch (      final Exception e) {
        callback.onResponseError(xml,e);
        e.printStackTrace();
      }
      receiveService.execute(createResponseAction(xml,callback,id,status,responseString));
    }
  }
;
}
 

Example 57

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

Source file: PooledHttpApiConnection.java

  31 
vote

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

Example 58

From project exo.social.client, under directory /src/main/java/org/exoplatform/social/client/api/util/.

Source file: SocialHttpClientSupport.java

  31 
vote

/** 
 * Invokes the social rest service via Post method
 * @param targetURL 
 * @param authPolicy POLICY.NO_AUTH/POLICY.BASIC_AUTH
 * @param params HttpParams for Request
 * @return
 * @throws IOException
 * @throws ClientProtocolException
 */
public static HttpResponse executePost(String targetURL,POLICY authPolicy,HttpParams params,Model model) throws SocialHttpClientException {
  HttpHost targetHost=new HttpHost(SocialClientContext.getHost(),SocialClientContext.getPort(),SocialClientContext.getProtocol());
  SocialHttpClient httpClient=SocialHttpClientImpl.newInstance();
  if (POLICY.BASIC_AUTH == authPolicy) {
    try {
      httpClient.setBasicAuthenticateToRequest();
    }
 catch (    SocialClientLibException e) {
      throw new SocialHttpClientException(e.getMessage(),e);
    }
  }
  HttpPost httpPost=new HttpPost(targetURL);
  Header header=new BasicHeader("Content-Type","application/json");
  httpPost.setHeader(header);
  if (params != null) {
    httpPost.setParams(params);
  }
  try {
    byte[] postData=convertModelToByteArray(model);
    if (postData != null) {
      ByteArrayEntity entity=new ByteArrayEntity(convertModelToByteArray(model));
      httpPost.setEntity(entity);
    }
    HttpResponse response=httpClient.execute(targetHost,httpPost);
    if (SocialClientContext.isDeveloping()) {
      dumpHttpResponsetHeader(response);
      dumpContent(response);
    }
    return response;
  }
 catch (  ClientProtocolException cpex) {
    throw new SocialHttpClientException(cpex.toString(),cpex);
  }
catch (  IOException ioex) {
    throw new SocialHttpClientException(ioex.toString(),ioex);
  }
}
 

Example 59

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

Source file: HttpClient.java

  31 
vote

/** 
 * Create request method, such as POST, GET, DELETE
 * @param httpMethod "GET","POST","DELETE"
 * @param uri ?????RI
 * @param file ???null
 * @param postParams POST???
 * @return httpMethod Request implementations for the various HTTP methodslike GET and POST.
 * @throws HttpException createMultipartEntity ? UrlEncodedFormEntity?????OException
 */
private HttpUriRequest createMethod(String httpMethod,URI uri,File file,ArrayList<BasicNameValuePair> postParams) throws HttpException {
  HttpUriRequest method;
  if (httpMethod.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
    HttpPost post=new HttpPost(uri);
    post.getParams().setBooleanParameter("http.protocol.expect-continue",false);
    try {
      HttpEntity entity=null;
      if (null != file) {
        entity=createMultipartEntity("photo",file,postParams);
        post.setEntity(entity);
      }
 else       if (null != postParams) {
        entity=new UrlEncodedFormEntity(postParams,HTTP.UTF_8);
      }
      post.setEntity(entity);
    }
 catch (    IOException ioe) {
      throw new HttpException(ioe.getMessage(),ioe);
    }
    method=post;
  }
 else   if (httpMethod.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
    method=new HttpDelete(uri);
  }
 else {
    method=new HttpGet(uri);
  }
  return method;
}
 

Example 60

From project Flume-Hive, under directory /src/java/com/cloudera/flume/handlers/hive/.

Source file: MarkerStore.java

  31 
vote

public boolean sendESQuery(String elasticSearchUrl,String sb){
  boolean success=true;
  LOG.info("sending batched stringentities");
  LOG.info("elasticSearchUrl: " + elasticSearchUrl);
  try {
    HttpClient httpClient=new DefaultHttpClient();
    HttpPost httpPost=new HttpPost(elasticSearchUrl);
    StringEntity se=new StringEntity(sb);
    httpPost.setEntity(se);
    HttpResponse hr=httpClient.execute(httpPost);
    LOG.info("HTTP Response: " + hr.getStatusLine());
    LOG.info("Closing httpConnection");
    httpClient.getConnectionManager().shutdown();
    LOG.info("booooooo: " + CharStreams.toString(new InputStreamReader(se.getContent())));
  }
 catch (  IOException e) {
    e.printStackTrace();
    success=false;
  }
 finally {
    if (!success) {
      LOG.info("ESQuery wasn't successful, writing to markerfolder");
      writeElasticSearchToMarkerFolder(new StringBuilder(sb));
    }
  }
  LOG.info("ESQuery was successful, yay!");
  return success;
}
 

Example 61

From project Fotolia-API, under directory /java/libs/httpcomponents-client-4.1.2/examples/org/apache/http/examples/client/.

Source file: ClientChunkEncodedPost.java

  31 
vote

public static void main(String[] args) throws Exception {
  if (args.length != 1) {
    System.out.println("File path not given");
    System.exit(1);
  }
  HttpClient httpclient=new DefaultHttpClient();
  try {
    HttpPost httppost=new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample");
    File file=new File(args[0]);
    InputStreamEntity reqEntity=new InputStreamEntity(new FileInputStream(file),-1);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(true);
    httppost.setEntity(reqEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response=httpclient.execute(httppost);
    HttpEntity resEntity=response.getEntity();
    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println("Response content length: " + resEntity.getContentLength());
      System.out.println("Chunked?: " + resEntity.isChunked());
    }
    EntityUtils.consume(resEntity);
  }
  finally {
    httpclient.getConnectionManager().shutdown();
  }
}
 

Example 62

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

Source file: LeonardoUpload.java

  31 
vote

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

Example 63

From project Game_3, under directory /android/src/playn/android/.

Source file: AndroidNet.java

  31 
vote

private void doHttp(final boolean isPost,final String url,final String data,final Callback<String> callback){
  new Thread("AndroidNet.doHttp"){
    public void run(){
      HttpClient httpclient=new DefaultHttpClient();
      HttpRequestBase req=null;
      if (isPost) {
        HttpPost httppost=new HttpPost(url);
        if (data != null) {
          try {
            httppost.setEntity(new StringEntity(data));
          }
 catch (          UnsupportedEncodingException e) {
            notifyFailure(callback,e);
          }
        }
        req=httppost;
      }
 else {
        req=new HttpGet(url);
      }
      try {
        HttpResponse response=httpclient.execute(req);
        notifySuccess(callback,EntityUtils.toString(response.getEntity()));
      }
 catch (      Exception e) {
        notifyFailure(callback,e);
      }
    }
  }
.start();
}
 

Example 64

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

Source file: CustomBugSenseReportSender.java

  31 
vote

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

Example 65

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

Source file: BookmarksQueryService.java

  31 
vote

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

Example 66

From project gpslogger, under directory /GPSLogger/src/com/mendhak/gpslogger/senders/osm/.

Source file: OSMHelper.java

  31 
vote

public void run(){
  try {
    HttpPost request=new HttpPost(gpsTraceUrl);
    consumer.sign(request);
    MultipartEntity entity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    FileBody gpxBody=new FileBody(chosenFile);
    entity.addPart("file",gpxBody);
    if (description == null || description.length() <= 0) {
      description="GPSLogger for Android";
    }
    entity.addPart("description",new StringBody(description));
    entity.addPart("tags",new StringBody(tags));
    entity.addPart("visibility",new StringBody(visibility));
    request.setEntity(entity);
    DefaultHttpClient httpClient=new DefaultHttpClient();
    HttpResponse response=httpClient.execute(request);
    int statusCode=response.getStatusLine().getStatusCode();
    Utilities.LogDebug("OSM Upload - " + String.valueOf(statusCode));
    helper.OnComplete();
  }
 catch (  Exception e) {
    helper.OnFailure();
    Utilities.LogError("OsmUploadHelper.run",e);
  }
}
 

Example 67

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

Source file: AppEngineClient.java

  31 
vote

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 68

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

Source file: Sender.java

  31 
vote

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

Example 69

From project hsDroid, under directory /src/de/nware/app/hsDroid/provider/.

Source file: onlineService2Provider.java

  31 
vote

/** 
 * Stellt HTTP Anfrage und liefert deren Antwort zur?ck.
 * @param url die formatierte URL
 * @return die HTML/XML Antwort
 * @throws Exception
 */
private synchronized String getResponse(String url){
  final HttpPost httpPost=new HttpPost(url);
  httpPost.addHeader("User-Agent",USER_AGENT);
  CookieSpecBase cookieSpecBase=new BrowserCompatSpec();
  List<Header> cookieHeader=cookieSpecBase.formatCookies(StaticSessionData.cookies);
  httpPost.setHeader(cookieHeader.get(0));
  int connectionTimeoutMillis=Integer.valueOf(StaticSessionData.sPreferences.getString(getContext().getString(R.string.Preference_ConnectionTimeout),"1500"));
  HttpClient client=HttpClientFactory.getHttpClient(connectionTimeoutMillis);
  try {
    final HttpResponse response=client.execute(httpPost);
    final StatusLine status=response.getStatusLine();
    if (status.getStatusCode() != HttpStatus.SC_OK) {
      Log.d(TAG,"http status code: " + status.getStatusCode());
      throw new RuntimeException("Ung?ltige Antwort vom Server: " + status.toString());
    }
    final HttpEntity entity=response.getEntity();
    final InputStream inputStream=entity.getContent();
    final ByteArrayOutputStream content=new ByteArrayOutputStream();
    int readBytes=0;
    while ((readBytes=inputStream.read(mContentBuffer)) != -1) {
      content.write(mContentBuffer,0,readBytes);
    }
    String output=new String(content.toByteArray());
    content.close();
    return output;
  }
 catch (  IOException e) {
    Log.d(TAG,e.getMessage());
    throw new RuntimeException("Verbindung fehlgeschlagen: " + e.getMessage(),e);
  }
}
 

Example 70

From project ihatovgram, under directory /src/client/android/ihatovgram/lib/httpcomponents-client-4.1.3/examples/org/apache/http/examples/client/.

Source file: ClientChunkEncodedPost.java

  31 
vote

public static void main(String[] args) throws Exception {
  if (args.length != 1) {
    System.out.println("File path not given");
    System.exit(1);
  }
  HttpClient httpclient=new DefaultHttpClient();
  try {
    HttpPost httppost=new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample");
    File file=new File(args[0]);
    InputStreamEntity reqEntity=new InputStreamEntity(new FileInputStream(file),-1);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(true);
    httppost.setEntity(reqEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response=httpclient.execute(httppost);
    HttpEntity resEntity=response.getEntity();
    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println("Response content length: " + resEntity.getContentLength());
      System.out.println("Chunked?: " + resEntity.isChunked());
    }
    EntityUtils.consume(resEntity);
  }
  finally {
    httpclient.getConnectionManager().shutdown();
  }
}
 

Example 71

From project jahspotify, under directory /services/src/main/java/jahspotify/services/spotiseek/.

Source file: SpotiseekService.java

  31 
vote

public SpotiseekResult search(String query){
  try {
    HttpClient httpClient=new DefaultHttpClient();
    final HttpPost httpPost=new HttpPost(_baseURL);
    final HttpResponse execute=httpClient.execute(httpPost);
    if (execute.getStatusLine().getStatusCode() == 200) {
      SAXParser saxParser=SAXParserFactory.newInstance().newSAXParser();
      saxParser.parse(execute.getEntity().getContent(),new SpotiseekResultContentHandler());
    }
    return null;
  }
 catch (  Exception e) {
    e.printStackTrace();
    throw new RuntimeException(e.getMessage(),e);
  }
}
 

Example 72

From project java-maven-tests, under directory /src/web-jdo/gdata-webapp-test/src/main/java/com/mysite/gdatatest/util/.

Source file: GoogleUtil.java

  31 
vote

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 73

From project jena-fuseki, under directory /src/main/java/org/apache/jena/fuseki/http/.

Source file: UpdateRemote.java

  31 
vote

public static void execute(UpdateRequest request,String serviceURL){
  HttpPost httpPost=new HttpPost(serviceURL);
  ByteArrayOutputStream b_out=new ByteArrayOutputStream();
  IndentedWriter out=new IndentedWriter(b_out);
  UpdateWriter.output(request,out);
  out.flush();
  byte[] bytes=b_out.toByteArray();
  AbstractHttpEntity reqEntity=new ByteArrayEntity(bytes);
  reqEntity.setContentType(WebContent.contentTypeSPARQLUpdate);
  reqEntity.setContentEncoding(HTTP.UTF_8);
  httpPost.setEntity(reqEntity);
  HttpClient httpclient=new DefaultHttpClient();
  try {
    HttpResponse response=httpclient.execute(httpPost);
    int responseCode=response.getStatusLine().getStatusCode();
    String responseMessage=response.getStatusLine().getReasonPhrase();
    if (responseCode == HttpSC.NO_CONTENT_204)     return;
    if (responseCode == HttpSC.OK_200)     return;
    throw new UpdateException(responseCode + " " + responseMessage);
  }
 catch (  IOException ex) {
    throw new UpdateException(ex);
  }
}
 

Example 74

From project amber, under directory /oauth-2.0/httpclient4/src/main/java/org/apache/amber/oauth2/httpclient4/.

Source file: HttpClient4.java

  30 
vote

public <T extends OAuthClientResponse>T execute(OAuthClientRequest request,Map<String,String> headers,String requestMethod,Class<T> responseClass) throws OAuthSystemException, OAuthProblemException {
  try {
    URI location=new URI(request.getLocationUri());
    HttpRequestBase req=null;
    String responseBody="";
    if (!OAuthUtils.isEmpty(requestMethod) && OAuth.HttpMethod.POST.equals(requestMethod)) {
      req=new HttpPost(location);
      HttpEntity entity=new StringEntity(request.getBody());
      ((HttpPost)req).setEntity(entity);
    }
 else {
      req=new HttpGet(location);
    }
    if (headers != null && !headers.isEmpty()) {
      for (      Map.Entry<String,String> header : headers.entrySet()) {
        req.setHeader(header.getKey(),header.getValue());
      }
    }
    HttpResponse response=client.execute(req);
    Header contentTypeHeader=null;
    HttpEntity entity=response.getEntity();
    if (entity != null) {
      responseBody=EntityUtils.toString(entity);
      contentTypeHeader=entity.getContentType();
    }
    String contentType=null;
    if (contentTypeHeader != null) {
      contentType=contentTypeHeader.toString();
    }
    return OAuthClientResponseFactory.createCustomResponse(responseBody,contentType,response.getStatusLine().getStatusCode(),responseClass);
  }
 catch (  Exception e) {
    throw new OAuthSystemException(e);
  }
}
 

Example 75

From project android_external_oauth, under directory /core/src/main/java/net/oauth/client/httpclient4/.

Source file: HttpClient4.java

  30 
vote

public HttpResponseMessage execute(HttpMessage request) throws IOException {
  final String method=request.method;
  final String url=request.url.toExternalForm();
  final InputStream body=request.getBody();
  final boolean isDelete=DELETE.equalsIgnoreCase(method);
  final boolean isPost=POST.equalsIgnoreCase(method);
  final boolean isPut=PUT.equalsIgnoreCase(method);
  byte[] excerpt=null;
  HttpRequestBase httpRequest;
  if (isPost || isPut) {
    HttpEntityEnclosingRequestBase entityEnclosingMethod=isPost ? new HttpPost(url) : new HttpPut(url);
    if (body != null) {
      ExcerptInputStream e=new ExcerptInputStream(body);
      excerpt=e.getExcerpt();
      String length=request.removeHeaders(HttpMessage.CONTENT_LENGTH);
      entityEnclosingMethod.setEntity(new InputStreamEntity(e,(length == null) ? -1 : Long.parseLong(length)));
    }
    httpRequest=entityEnclosingMethod;
  }
 else   if (isDelete) {
    httpRequest=new HttpDelete(url);
  }
 else {
    httpRequest=new HttpGet(url);
  }
  for (  Map.Entry<String,String> header : request.headers) {
    httpRequest.addHeader(header.getKey(),header.getValue());
  }
  HttpClient client=clientPool.getHttpClient(new URL(httpRequest.getURI().toString()));
  client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS,false);
  HttpResponse httpResponse=client.execute(httpRequest);
  return new HttpMethodResponse(httpRequest,httpResponse,excerpt,request.getContentCharset());
}
 

Example 76

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

Source file: AudioBox.java

  30 
vote

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

Example 77

From project httpbuilder, under directory /src/main/java/groovyx/net/http/.

Source file: HTTPBuilder.java

  29 
vote

/** 
 * <p> Convenience method to perform an HTTP form POST.  The response closure will be  called only on a successful response.</p>    <p>A 'failed' response (i.e. any  HTTP status code > 399) will be handled by the registered 'failure'  handler.  The  {@link #defaultFailureHandler(HttpResponseDecorator) default failure handler} throws an {@link HttpResponseException}.</p>   <p>The request body (specified by a <code>body</code> named parameter)  will be converted to a url-encoded form string unless a different  <code>requestContentType</code> named parameter is passed to this method. (See  {@link EncoderRegistry#encodeForm(Map)}.) </p>
 * @param args see {@link RequestConfigDelegate#setPropertiesFromMap(Map)}
 * @param responseClosure code to handle a successful HTTP response
 * @return any value returned by the response closure.
 * @throws ClientProtocolException
 * @throws IOException
 * @throws URISyntaxException if a uri argument is given which does not represent a valid URI
 */
public Object post(Map<String,?> args,Closure responseClosure) throws URISyntaxException, ClientProtocolException, IOException {
  RequestConfigDelegate delegate=new RequestConfigDelegate(new HttpPost(),this.defaultContentType,this.defaultRequestHeaders,this.defaultResponseHandlers);
  delegate.setRequestContentType(ContentType.URLENC.toString());
  delegate.setPropertiesFromMap(args);
  if (responseClosure != null)   delegate.getResponse().put(Status.SUCCESS.toString(),responseClosure);
  return this.doRequest(delegate);
}