Java Code Examples for org.apache.http.util.EntityUtils

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 BF3-Battlelog, under directory /src/com/ninetwozero/battlelog/http/.

Source file: RequestHandler.java

  16 
vote

public String get(String link,int extraHeaders) throws RequestHandlerException {
  if ("".equals(link)) {
    throw new RequestHandlerException("No link found.");
  }
  try {
    HttpGet httpGet=new HttpGet(link.replace(" ","%20"));
    httpGet.setHeaders(HttpHeaders.GET_HEADERS.get(extraHeaders));
    httpGet.setHeader("Referer",link);
    HttpResponse httpResponse=RequestHandler.httpClient.execute(httpGet);
    HttpEntity httpEntity=httpResponse.getEntity();
    if (httpEntity != null) {
      return EntityUtils.toString(httpEntity);
    }
  }
 catch (  ClientProtocolException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
catch (  Exception ex) {
    throw new RequestHandlerException(ex.getMessage());
  }
  return "";
}
 

Example 2

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

Source file: C2dmHttpResponseHandler.java

  16 
vote

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

Example 3

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

Source file: SGS.java

  15 
vote

public void detectCharacterEncoding(){
  HttpGet get;
  HttpResponse response;
  Header contentType;
  Pattern pattern;
  Matcher matcher;
  try {
    get=new HttpGet(baseUrl + homeAction);
    response=client.execute(get);
    contentType=response.getFirstHeader("Content-Type");
    EntityUtils.consume(response.getEntity());
    if (contentType == null || contentType.getValue() == null) {
      characterEncoding="ISO-8859-1";
    }
    pattern=Pattern.compile(".*charset=(.+)");
    matcher=pattern.matcher(contentType.getValue());
    if (!matcher.matches()) {
      characterEncoding="ISO-8859-1";
    }
    characterEncoding=matcher.group(1);
  }
 catch (  Exception e) {
    characterEncoding="ISO-8859-1";
  }
}
 

Example 4

From project accounted4, under directory /accounted4/stock-quote/stock-quote-yahoo/src/main/java/com/accounted4/stockquote/yahoo/.

Source file: YahooQuoteService.java

  15 
vote

@Override public List<HashMap<QuoteAttribute,String>> executeQuery(List<String> securityList,List<QuoteAttribute> quoteAttributes){
  String tickerList=securityListToString(securityList);
  String attributeList=attributeListToString(quoteAttributes);
  HttpClient httpclient=new DefaultHttpClient();
  String urlString=BASE_URL + "?" + "s="+ tickerList+ "&"+ "f="+ attributeList;
  System.out.println("Query url: " + urlString);
  HttpGet httpGet=new HttpGet(urlString);
  try {
    HttpResponse response=httpclient.execute(httpGet);
    HttpEntity entity=response.getEntity();
    if (entity != null) {
      String stringResponse=EntityUtils.toString(entity);
      return processResponse(stringResponse,quoteAttributes);
    }
  }
 catch (  IOException ex) {
    System.out.println("Error " + ex);
  }
  List<HashMap<QuoteAttribute,String>> result=new ArrayList<>();
  return result;
}
 

Example 5

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

Source file: HttpClient4.java

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

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

Source file: AsyncHttpResponseHandler.java

  15 
vote

void sendResponseMessage(HttpResponse response){
  StatusLine status=response.getStatusLine();
  String responseBody=null;
  try {
    HttpEntity entity=null;
    HttpEntity temp=response.getEntity();
    if (temp != null) {
      entity=new BufferedHttpEntity(temp);
      responseBody=EntityUtils.toString(entity,"UTF-8");
    }
  }
 catch (  IOException e) {
    sendFailureMessage(e,(String)null);
  }
  if (status.getStatusCode() >= 300) {
    sendFailureMessage(new HttpResponseException(status.getStatusCode(),status.getReasonPhrase()),responseBody);
  }
 else {
    sendSuccessMessage(responseBody);
  }
}
 

Example 7

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

Source file: Chalmrest.java

  15 
vote

@Override public void update() throws BankException, LoginException, BankChoiceException {
  super.update();
  if (username == null || username.length() == 0)   throw new LoginException(res.getText(R.string.invalid_username_password).toString());
  try {
    String cardNr=username;
    HttpClient httpclient=new DefaultHttpClient();
    HttpGet httpget=new HttpGet("http://kortladdning.chalmerskonferens.se/bgw.aspx?type=getCardAndArticles&card=" + cardNr);
    HttpResponse response=httpclient.execute(httpget);
    HttpEntity entity=response.getEntity();
    if (entity == null)     throw new BankException("Couldn't connect!");
    String s1=EntityUtils.toString(entity);
    Pattern pattern=Pattern.compile("<ExtendedInfo Name=\"Kortvarde\" Type=\"System.Double\" >(.*?)</ExtendedInfo>");
    Matcher matcher=pattern.matcher(s1);
    if (!matcher.find())     throw new BankException("Couldn't parse value!");
    String value=matcher.group(1);
    StringBuilder sb=new StringBuilder();
    int last=0;
    Matcher match=Pattern.compile("_x([0-9A-Fa-f]{4})_").matcher(value);
    while (match.find()) {
      sb.append(value.substring(last,Math.max(match.start() - 1,0)));
      int i=Integer.parseInt(match.group(1),16);
      sb.append((char)i);
      last=match.end();
    }
    sb.append(value.substring(last));
    value=sb.toString();
    matcher=Pattern.compile("<CardInfo id=\"" + cardNr + "\" Name=\"(.*?)\"").matcher(s1);
    if (!matcher.find())     throw new BankException("Coldn't parse name!");
    String name=matcher.group(1);
    accounts.add(new Account(name,BigDecimal.valueOf(Double.parseDouble(value)),"1"));
  }
 catch (  Exception e) {
    throw new BankException(e.getMessage());
  }
 finally {
    super.updateComplete();
  }
}
 

Example 8

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

Source file: HttpConnector.java

  15 
vote

private <T extends Resource>T buildResource(Class<T> ofType,HttpEntity from){
  Serializer serializer=new Persister();
  T res=null;
  try {
    res=serializer.read(ofType,EntityUtils.toString(from));
    from.consumeContent();
  }
 catch (  Exception e) {
    Log.e(TAG,e.getMessage());
  }
  return res;
}
 

Example 9

From project android-rackspacecloud, under directory /src/com/rackspace/cloud/servers/api/client/http/.

Source file: HttpBundle.java

  15 
vote

public String getResponseText(){
  HttpEntity responseEntity=response.getEntity();
  StringBuilder result=new StringBuilder();
  HeaderIterator itr=response.headerIterator();
  while (itr.hasNext()) {
    result.append(itr.nextHeader() + "\n");
  }
  String xml="\n\n";
  try {
    xml=EntityUtils.toString(responseEntity);
  }
 catch (  ParseException e1) {
    e1.printStackTrace();
  }
catch (  IOException e1) {
    e1.printStackTrace();
  }
  result.append(xml);
  return result.toString();
}
 

Example 10

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

Source file: NetworkUtilities.java

  15 
vote

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

Example 11

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

Source file: HttpSupport.java

  15 
vote

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

Example 12

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

Source file: JoinServiceBase.java

  15 
vote

protected static String getUrl(HttpClient client,String url) throws IOException, ClientProtocolException {
  HttpGet method=new HttpGet(url);
  HttpResponse httpResponse=client.execute(method);
  if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK)   log.debug("HTTP GET {} return {}",url,httpResponse.getStatusLine().getStatusCode());
  return EntityUtils.toString(httpResponse.getEntity()).trim();
}
 

Example 13

From project components-ness-httpclient, under directory /client/src/main/java/com/nesscomputing/httpclient/factory/httpclient4/.

Source file: InternalResponse.java

  15 
vote

@Override public String getCharset(){
  if (httpResponse != null) {
    final HttpEntity entity=httpResponse.getEntity();
    if (entity != null) {
      return EntityUtils.getContentCharSet(entity);
    }
  }
  return null;
}
 

Example 14

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

Source file: ErrorPreservingResponseHandler.java

  15 
vote

public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
  final StatusLine statusLine=response.getStatusLine();
  final HttpEntity entity=response.getEntity();
  final String str=entity == null ? null : EntityUtils.toString(entity);
  if (statusLine.getStatusCode() >= 300) {
    throw new HttpResponseException(statusLine.getStatusCode(),str);
  }
  return str;
}
 

Example 15

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

Source file: CouchResponse.java

  15 
vote

/** 
 * C-tor parses the method results to build the CouchResponse object. First, it reads the body (hence the IOException) from the method Next, it checks the status codes to determine if the request was successful. If there was an error, it parses the error codes.
 * @param method
 * @throws IOException
 */
CouchResponse(HttpRequestBase req,HttpResponse response) throws IOException {
  headers=response.getAllHeaders();
  HttpEntity entity=response.getEntity();
  body=EntityUtils.toString(entity);
  path=req.getURI().getPath();
  statusCode=response.getStatusLine().getStatusCode();
  boolean isGet=(req instanceof HttpGet);
  boolean isPut=(req instanceof HttpPut);
  boolean isPost=(req instanceof HttpPost);
  boolean isDelete=(req instanceof HttpDelete);
  if ((isGet && statusCode == 404) || (isPut && statusCode == 409) || (isPost && statusCode == 404)|| (isDelete && statusCode == 404)) {
    JSONObject jbody=JSONObject.fromObject(body);
    error_id=jbody.getString("error");
    error_reason=jbody.getString("reason");
  }
 else   if ((isPut && statusCode == 201) || (isPost && statusCode == 201) || (isDelete && statusCode == 202)|| (isDelete && statusCode == 200)) {
    if (path.endsWith("_bulk_docs")) {
      ok=JSONArray.fromObject(body).size() > 0;
    }
 else {
      ok=JSONObject.fromObject(body).getBoolean("ok");
    }
  }
 else   if ((req instanceof HttpGet) || ((req instanceof HttpPost) && statusCode == 200)) {
    ok=true;
  }
  log.debug(toString());
}
 

Example 16

From project crawler4j, under directory /src/main/java/edu/uci/ics/crawler4j/crawler/.

Source file: Page.java

  15 
vote

/** 
 * Loads the content of this page from a fetched HttpEntity.
 */
public void load(HttpEntity entity) throws Exception {
  contentType=null;
  Header type=entity.getContentType();
  if (type != null) {
    contentType=type.getValue();
  }
  contentEncoding=null;
  Header encoding=entity.getContentEncoding();
  if (encoding != null) {
    contentEncoding=encoding.getValue();
  }
  contentCharset=EntityUtils.getContentCharSet(entity);
  contentData=EntityUtils.toByteArray(entity);
}
 

Example 17

From project cw-android, under directory /Service/Downloader/src/com/commonsware/android/downloader/.

Source file: ByteArrayResponseHandler.java

  15 
vote

public byte[] handleResponse(final HttpResponse response) throws IOException, HttpResponseException {
  StatusLine statusLine=response.getStatusLine();
  if (statusLine.getStatusCode() >= 300) {
    throw new HttpResponseException(statusLine.getStatusCode(),statusLine.getReasonPhrase());
  }
  HttpEntity entity=response.getEntity();
  if (entity == null) {
    return (null);
  }
  return (EntityUtils.toByteArray(entity));
}
 

Example 18

From project cw-omnibus, under directory /Power/Downloader/src/com/commonsware/android/tuning/downloader/.

Source file: ByteArrayResponseHandler.java

  15 
vote

public byte[] handleResponse(final HttpResponse response) throws IOException, HttpResponseException {
  StatusLine statusLine=response.getStatusLine();
  if (statusLine.getStatusCode() >= 300) {
    throw new HttpResponseException(statusLine.getStatusCode(),statusLine.getReasonPhrase());
  }
  HttpEntity entity=response.getEntity();
  if (entity == null) {
    return (null);
  }
  return (EntityUtils.toByteArray(entity));
}
 

Example 19

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

Source file: HTTPUtil.java

  15 
vote

public static String readURL(String url){
  HttpGet request=new HttpGet(url);
  HttpClient httpClient=new DefaultHttpClient();
  try {
    HttpResponse response=httpClient.execute(request);
    return EntityUtils.toString(response.getEntity());
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 20

From project dccsched, under directory /src/com/underhilllabs/dccsched/ui/.

Source file: SessionDetailActivity.java

  15 
vote

@Override protected String doInBackground(String... params){
  final String param=params[0];
  try {
    final Context context=SessionDetailActivity.this;
    final HttpClient httpClient=getHttpClient(context);
    final HttpResponse resp=httpClient.execute(new HttpGet(param));
    final HttpEntity entity=resp.getEntity();
    final int statusCode=resp.getStatusLine().getStatusCode();
    if (statusCode != HttpStatus.SC_OK || entity == null)     return null;
    final String respString=EntityUtils.toString(entity);
    final JSONObject respJson=new JSONObject(respString);
    final JSONObject data=respJson.getJSONObject("data");
    final JSONObject counters=respJson.getJSONObject("counters");
    final int questions=counters.getInt("submissions");
    final int votes=counters.getInt("noteVotes") + counters.getInt("plusVotes") + counters.getInt("minusVotes");
    return getString(R.string.session_moderator_status,questions,votes);
  }
 catch (  Exception e) {
    Log.w(TAG,"Problem while loading Moderator status: " + e.toString());
  }
  return null;
}
 

Example 21

From project DeliciousDroid, under directory /src/com/deliciousdroid/client/.

Source file: DeliciousFeed.java

  15 
vote

/** 
 * Retrieves a list of contacts in a users network.
 * @param account The account being synced.
 * @return The list of contacts received from the server.
 * @throws JSONException If an error was encountered in deserializing the JSON object returned from the server.
 * @throws IOException If a server error was encountered.
 * @throws AuthenticationException If an authentication error was encountered.
 */
public static List<User> fetchFriendUpdates(Account account) throws JSONException, IOException, AuthenticationException, FeedForbiddenException {
  final ArrayList<User> friendList=new ArrayList<User>();
  final HttpGet post=new HttpGet(FETCH_FRIEND_UPDATES_URI + account.name);
  final HttpResponse resp=HttpClientFactory.getThreadSafeClient().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     if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
      Log.e(TAG,"Fetching contact updates forbidden");
      throw new FeedForbiddenException();
    }
 else {
      Log.e(TAG,"Server error in fetching remote contacts: " + resp.getStatusLine());
      throw new IOException();
    }
  }
  return friendList;
}
 

Example 22

From project devoxx-france-android-in-fine, under directory /src/com/infine/android/devoxx/util/lazy/.

Source file: ImageLoader.java

  15 
vote

private Bitmap getBitmap(String url){
  File f=fileCache.getFile(url);
  Bitmap b=decodeFile(f);
  if (b != null)   return b;
  try {
    final HttpClient httpClient=HttpHelper.getHttpClient();
    final HttpResponse resp=httpClient.execute(new HttpGet(url));
    final HttpEntity entity=resp.getEntity();
    final int statusCode=resp.getStatusLine().getStatusCode();
    if (statusCode != HttpStatus.SC_OK || entity == null) {
      return null;
    }
    final byte[] respBytes=EntityUtils.toByteArray(entity);
    if (f != null) {
      try {
        FileOutputStream fos=new FileOutputStream(f);
        fos.write(respBytes);
        fos.close();
      }
 catch (      FileNotFoundException e) {
        Log.w(TAG,"Error writing to bitmap cache: " + f.toString(),e);
      }
catch (      IOException e) {
        Log.w(TAG,"Error writing to bitmap cache: " + f.toString(),e);
      }
    }
    Bitmap bitmap=decodeFile(f);
    return bitmap;
  }
 catch (  Exception ex) {
    Log.e(TAG,"Error retrieving image ",ex);
    return null;
  }
}
 

Example 23

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

Source file: NetworkHelper.java

  15 
vote

public String doHTTPGet(String uri){
  Log.d("Discogs","Requesting:" + uri);
  String response=null;
  HttpGet hTTPGet=new HttpGet(uri);
  try {
    consumer.sign(hTTPGet);
    HttpResponse hTTPResponse=httpClient.execute(hTTPGet);
    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 24

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

Source file: ConexionSii.java

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

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

Source file: HttpConnector.java

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

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

Source file: SocialHttpClientSupport.java

  15 
vote

/** 
 * Executes the HttpResponse with read the content to buffered.
 * @param response HttpResponse to process.
 * @return Content of HttpResponse.
 * @throws IllegalStateException
 * @throws IOException
 */
public static String getContent(HttpResponse response) throws SocialHttpClientException {
  if (response == null) {
    throw new NullPointerException("HttpResponse argument is not NULL.");
  }
  HttpEntity entity=processContent(response);
  String content;
  try {
    if (entity.getContentLength() != -1) {
      content=EntityUtils.toString(entity);
    }
 else {
      throw new SocialHttpClientException("Content of response is empty.");
    }
  }
 catch (  IOException ioex) {
    throw new SocialHttpClientException(ioex.toString(),ioex);
  }
  return content;
}
 

Example 27

From project fed4j, under directory /src/main/java/com/jute/fed4j/engine/component/http/.

Source file: HttpDispatcherImpl_Jakarta.java

  15 
vote

/** 
 * Returns the response body as a String if the response was successful (a 2xx status code). If no response body exists, this returns null. If the response was unsuccessful (>= 300 status code), throws an {@link org.apache.http.client.HttpResponseException}.
 */
public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
  StatusLine statusLine=response.getStatusLine();
  code=statusLine.getStatusCode();
  headers=response.getAllHeaders();
  if (statusLine.getStatusCode() >= 300) {
    throw new HttpResponseException(statusLine.getStatusCode(),statusLine.getReasonPhrase());
  }
  HttpEntity entity=response.getEntity();
  return entity == null ? null : EntityUtils.toString(entity,responseCharset);
}
 

Example 28

From project flazr, under directory /src/main/java/com/flazr/util/.

Source file: Utils.java

  15 
vote

public static String getOverHttp(String url){
  HttpClient client=new DefaultHttpClient();
  HttpGet method=new HttpGet(url);
  String result=null;
  try {
    HttpResponse response=client.execute(method);
    result=EntityUtils.toString(response.getEntity());
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return result;
}
 

Example 29

From project FlickrCity, under directory /src/com/FlickrCity/FlickrCityAndroid/Activities/.

Source file: PhotoActivity.java

  15 
vote

private FlickrPhoto getFlickrPhotoByID(String photo_id){
  String url="http://api.flickr.com/services/rest/?method=flickr.photos.getInfo" + "&api_key=" + Constants.API_KEY + "&photo_id="+ photo_id+ "&format=json&nojsoncallback=1";
  String json_response=null;
  try {
    HttpClient client=new DefaultHttpClient();
    HttpGet httpGet=new HttpGet(url);
    HttpResponse response=client.execute(httpGet);
    StatusLine statusLine=response.getStatusLine();
    int statusCode=statusLine.getStatusCode();
    if (statusCode == 200) {
      json_response=EntityUtils.toString(response.getEntity());
    }
  }
 catch (  Exception e) {
  }
  if (json_response == null)   return null;
 else {
    final FlickrPhoto photo=new FlickrPhoto();
    try {
      JSONObject jobj=new JSONObject(json_response);
      photo.setOwner(jobj.getJSONObject("photo").getJSONObject("owner").getString("username"));
      photo.setTitle(jobj.getJSONObject("photo").getJSONObject("title").getString("_content"));
    }
 catch (    Exception e) {
    }
    return photo;
  }
}
 

Example 30

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

Source file: GReader.java

  15 
vote

public void getSidAndAuth(String email,String password) throws HttpException, IOException {
  setEmail(email);
  setPassword(password);
  setAuth_params();
  String sidtag="SID=";
  String authtag="Auth=";
  HttpPost post=new HttpPost(GOOGLE_READER);
  post.setHeader("Content-Type","application/x-www-form-urlencoded");
  HttpEntity entity=new UrlEncodedFormEntity(paramsNameValuePairs,HTTP.UTF_8);
  post.setEntity(entity);
  HttpResponse response=null;
  HttpClient httpclient=new DefaultHttpClient();
  response=httpclient.execute(post);
  int result=response.getStatusLine().getStatusCode();
  if (result == 200) {
    loginstate=200;
    String[] temps=EntityUtils.toString(response.getEntity()).split("\n");
    for (    String temp : temps) {
      if (temp.startsWith(sidtag))       this.sid=temp.substring(sidtag.length());
 else       if (temp.startsWith(authtag))       this.auth=temp.substring(authtag.length());
    }
    isRight();
  }
  post.abort();
  httpclient.getConnectionManager().shutdown();
  httpclient=null;
}
 

Example 31

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

Source file: ClientAuthentication.java

  15 
vote

public static void main(String[] args) throws Exception {
  DefaultHttpClient httpclient=new DefaultHttpClient();
  try {
    httpclient.getCredentialsProvider().setCredentials(new AuthScope("localhost",443),new UsernamePasswordCredentials("username","password"));
    HttpGet httpget=new HttpGet("https://localhost/protected");
    System.out.println("executing request" + httpget.getRequestLine());
    HttpResponse response=httpclient.execute(httpget);
    HttpEntity entity=response.getEntity();
    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    if (entity != null) {
      System.out.println("Response content length: " + entity.getContentLength());
    }
    EntityUtils.consume(entity);
  }
  finally {
    httpclient.getConnectionManager().shutdown();
  }
}
 

Example 32

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

Source file: LeonardoUpload.java

  15 
vote

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

Example 33

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

Source file: AndroidNet.java

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

From project GeekAlarm, under directory /android/src/com/geek_alarm/android/tasks/.

Source file: TaskManager.java

  15 
vote

public static List<TaskType> getTaskTypes() throws Exception {
  String jsonText=EntityUtils.toString(sendRequest("tasks"));
  JSONArray array=new JSONArray(jsonText);
  List<TaskType> taskTypes=new ArrayList<TaskType>();
  for (int i=0; i < array.length(); i++) {
    taskTypes.add(jsonToTaskType(array.getJSONObject(i)));
  }
  return taskTypes;
}
 

Example 35

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

Source file: WebService.java

  15 
vote

private String webInvoke(String methodName,String data,String contentType){
  ret=null;
  httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.RFC_2109);
  httpPost=new HttpPost(webServiceUrl + methodName);
  response=null;
  StringEntity tmp=null;
  httpPost.setHeader("Accept","text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
  if (contentType != null) {
    httpPost.setHeader("Content-Type",contentType);
  }
 else {
    httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");
  }
  try {
    tmp=new StringEntity(data,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
    Log.e(TAG,"HttpUtils : UnsupportedEncodingException : " + e);
  }
  httpPost.setEntity(tmp);
  if (LOGGING.DEBUG)   Log.d(TAG,webServiceUrl + "?" + data);
  try {
    response=httpClient.execute(httpPost,localContext);
    if (response != null) {
      ret=EntityUtils.toString(response.getEntity());
    }
  }
 catch (  Exception e) {
    Log.e(TAG,"HttpUtils: " + e);
  }
  return ret;
}
 

Example 36

From project gnip4j, under directory /http/src/main/java/com/zaubersoftware/gnip4j/http/.

Source file: HttpResponseReleaseInputStream.java

  15 
vote

@Override public void close() throws IOException {
  try {
    if (target != null) {
      try {
        target.close();
        target=null;
      }
 catch (      IOException e) {
      }
    }
  }
  finally {
    if (entity != null) {
      try {
        EntityUtils.consume(entity);
        entity=null;
      }
 catch (      final IOException e) {
      }
    }
  }
}
 

Example 37

From project httpClient, under directory /ctct/src/main/java/weden/jason/qa/ctct/.

Source file: HttpConnector.java

  15 
vote

protected String getBody(HttpResponse resp) throws IOException {
  HttpEntity entity=resp.getEntity();
  StringBuilder bodyBuilder=new StringBuilder();
  if (entity != null) {
    long len=entity.getContentLength();
    if (len != -1 && len < 2048) {
      bodyBuilder.append(EntityUtils.toString(entity));
    }
 else {
      BufferedReader in=new BufferedReader(new InputStreamReader(entity.getContent()));
      String line;
      while ((line=in.readLine()) != null) {
        bodyBuilder.append(line);
        bodyBuilder.append(newLine);
      }
    }
  }
  return bodyBuilder.toString();
}
 

Example 38

From project httpcore, under directory /httpcore/src/examples/org/apache/http/examples/.

Source file: ElementalHttpGet.java

  15 
vote

public static void main(String[] args) throws Exception {
  HttpProcessor httpproc=new ImmutableHttpProcessor(new HttpRequestInterceptor[]{new RequestContent(),new RequestTargetHost(),new RequestConnControl(),new RequestUserAgent("Test/1.1"),new RequestExpectContinue()});
  HttpRequestExecutor httpexecutor=new HttpRequestExecutor();
  HttpCoreContext context=new HttpCoreContext();
  HttpHost host=new HttpHost("localhost",8080);
  context.setTarget(host);
  context.setExpectContinue();
  DefaultBHttpClientConnection conn=new DefaultBHttpClientConnection(8 * 1024);
  ConnectionReuseStrategy connStrategy=DefaultConnectionReuseStrategy.INSTANCE;
  try {
    String[] targets={"/","/servlets-examples/servlet/RequestInfoExample","/somewhere%20in%20pampa"};
    for (int i=0; i < targets.length; i++) {
      if (!conn.isOpen()) {
        Socket socket=new Socket(host.getHostName(),host.getPort());
        conn.bind(socket);
      }
      BasicHttpRequest request=new BasicHttpRequest("GET",targets[i]);
      System.out.println(">> Request URI: " + request.getRequestLine().getUri());
      httpexecutor.preProcess(request,httpproc,context);
      HttpResponse response=httpexecutor.execute(request,conn,context);
      httpexecutor.postProcess(response,httpproc,context);
      System.out.println("<< Response: " + response.getStatusLine());
      System.out.println(EntityUtils.toString(response.getEntity()));
      System.out.println("==============");
      if (!connStrategy.keepAlive(response,context)) {
        conn.close();
      }
 else {
        System.out.println("Connection kept alive...");
      }
    }
  }
  finally {
    conn.close();
  }
}