List of usage examples for org.apache.http.client.methods HttpUriRequest addHeader
void addHeader(String str, String str2);
From source file:com.fujitsu.dc.client.http.DcRequestBuilder.java
/** * This method is used to generate a HttpUriRequest object by setting the parameters in request header. * @return HttpUriRequest object that is generated * @throws DaoException Exception thrown *///from w w w . j a v a 2 s . co m public HttpUriRequest build() throws DaoException { HttpUriRequest req = null; if (HttpMethods.PUT.equals(this.methodValue)) { req = new HttpPut(this.urlValue); } else if (HttpMethods.POST.equals(this.methodValue)) { req = new HttpPost(this.urlValue); } else if (HttpMethods.DELETE.equals(this.methodValue)) { req = new HttpDelete(this.urlValue); } else if (HttpMethods.ACL.equals(this.methodValue)) { req = new HttpAclMethod(this.urlValue); } else if (HttpMethods.MKCOL.equals(this.methodValue)) { req = new HttpMkColMethod(this.urlValue); } else if (HttpMethods.PROPPATCH.equals(this.methodValue)) { req = new HttpPropPatchMethod(this.urlValue); } else if (HttpMethods.PROPFIND.equals(this.methodValue)) { req = new HttpPropfindMethod(this.urlValue); } else if (HttpMethods.GET.equals(this.methodValue)) { req = new HttpGet(this.urlValue); } else if (HttpMethods.MERGE.equals(this.methodValue)) { req = new HttpMergeMethod(this.urlValue); } if (this.tokenValue != null) { req.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + this.tokenValue); } /** include header parameters if any. */ for (String key : headers.keySet()) { String value = headers.get(key); req.addHeader(key, value); } // ???????? /** If Default header is set, configure them. */ // ????????????????????? /** * The reason you do not want to set for the first time, since the request header, would have been more than one * registration is the same name header */ if (this.defaultHeaders != null) { for (String key : this.defaultHeaders.keySet()) { String val = this.defaultHeaders.get(key); Header[] headerItems = req.getHeaders(key); if (headerItems.length == 0) { req.addHeader(key, val); } } } if (this.bodyValue != null) { HttpEntity body = null; try { if (this.getContentType() != "" && RestAdapter.CONTENT_TYPE_JSON.equals(this.getContentType())) { String bodyStr = toUniversalCharacterNames(this.bodyValue); body = new StringEntity(bodyStr); } else { body = new StringEntity(this.bodyValue, RestAdapter.ENCODE); } } catch (UnsupportedEncodingException e) { throw DaoException.create("error while request body encoding : " + e.getMessage(), 0); } ((HttpEntityEnclosingRequest) req).setEntity(body); } if (this.bodyStream != null) { InputStreamEntity body = new InputStreamEntity(this.bodyStream, -1); body.setChunked(true); this.bodyValue = "[stream]"; ((HttpEntityEnclosingRequest) req).setEntity(body); } if (req != null) { log.debug(""); log.debug("?Request " + req.getMethod() + " " + req.getURI()); Header[] allheaders = req.getAllHeaders(); for (int i = 0; i < allheaders.length; i++) { log.debug("RequestHeader[" + allheaders[i].getName() + "] : " + allheaders[i].getValue()); } log.debug("RequestBody : " + bodyValue); } return req; }
From source file:org.openrdf.http.client.SparqlSession.java
private HttpResponse sendBooleanQueryViaHttp(HttpUriRequest method, Set<BooleanQueryResultFormat> booleanFormats) throws IOException, OpenRDFException { for (BooleanQueryResultFormat format : booleanFormats) { // Determine a q-value that reflects the user specified preference int qValue = 10; if (preferredBQRFormat != null && !preferredBQRFormat.equals(format)) { // Prefer specified format over other formats qValue -= 2;//ww w .ja v a2 s . c o m } for (String mimeType : format.getMIMETypes()) { String acceptParam = mimeType; if (qValue < 10) { acceptParam += ";q=0." + qValue; } method.addHeader(ACCEPT_PARAM_NAME, acceptParam); } } return executeOK(method); }
From source file:org.b3log.latke.urlfetch.bae.BAEURLFetchService.java
@Override public HTTPResponse fetch(final HTTPRequest request) throws IOException { final HttpClient httpClient = new DefaultHttpClient(); final URL url = request.getURL(); final HTTPRequestMethod requestMethod = request.getRequestMethod(); HttpUriRequest httpUriRequest = null; try {// ww w.j a v a 2 s . c o m final byte[] payload = request.getPayload(); switch (requestMethod) { case GET: final HttpGet httpGet = new HttpGet(url.toURI()); // FIXME: GET with payload httpUriRequest = httpGet; break; case DELETE: httpUriRequest = new HttpDelete(url.toURI()); break; case HEAD: httpUriRequest = new HttpHead(url.toURI()); break; case POST: final HttpPost httpPost = new HttpPost(url.toURI()); if (null != payload) { httpPost.setEntity(new ByteArrayEntity(payload)); } httpUriRequest = httpPost; break; case PUT: final HttpPut httpPut = new HttpPut(url.toURI()); if (null != payload) { httpPut.setEntity(new ByteArrayEntity(payload)); } httpUriRequest = httpPut; break; default: throw new RuntimeException("Unsupported HTTP request method[" + requestMethod.name() + "]"); } } catch (final Exception e) { LOGGER.log(Level.SEVERE, "URL fetch failed", e); throw new IOException("URL fetch failed [msg=" + e.getMessage() + ']'); } final List<HTTPHeader> headers = request.getHeaders(); for (final HTTPHeader header : headers) { httpUriRequest.addHeader(header.getName(), header.getValue()); } final HttpResponse res = httpClient.execute(httpUriRequest); final HTTPResponse ret = new HTTPResponse(); ret.setContent(EntityUtils.toByteArray(res.getEntity())); ret.setResponseCode(res.getStatusLine().getStatusCode()); return ret; }
From source file:com.akop.bach.parser.PsnUsParser.java
protected ContentValues parseSummaryData(PsnAccount account) throws IOException, ParserException { long started = System.currentTimeMillis(); String url = String.format(URL_PROFILE_SUMMARY, Math.random()); HttpUriRequest request = new HttpGet(url); request.addHeader("Referer", "http://us.playstation.com/mytrophies/index.htm"); request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); String page = getResponse(request, null); if (App.getConfig().logToConsole()) started = displayTimeTaken("parseSummaryData page fetch", started); ContentValues cv = new ContentValues(10); Matcher m;/* w w w. j av a 2 s .c o m*/ if (!(m = PATTERN_ONLINE_ID.matcher(page)).find()) throw new ParserException(mContext, R.string.error_online_id_not_detected); cv.put(Profiles.ONLINE_ID, m.group(1)); int level = 0; if ((m = PATTERN_LEVEL.matcher(page)).find()) level = Integer.parseInt(m.group(1)); int progress = 0; if ((m = PATTERN_PROGRESS.matcher(page)).find()) progress = Integer.parseInt(m.group(1)); int trophiesPlat = 0; int trophiesGold = 0; int trophiesSilver = 0; int trophiesBronze = 0; if ((m = PATTERN_URL_TROPHIES.matcher(page)).find()) { String queryString = m.group(1); String[] pairs = queryString.split("&"); for (String pair : pairs) { String[] param = pair.split("="); if (param.length > 1) { if (param[0].equalsIgnoreCase("bronze")) trophiesBronze = Integer.parseInt(param[1]); else if (param[0].equalsIgnoreCase("silver")) trophiesSilver = Integer.parseInt(param[1]); else if (param[0].equalsIgnoreCase("gold")) trophiesGold = Integer.parseInt(param[1]); else if (param[0].equalsIgnoreCase("platinum")) trophiesPlat = Integer.parseInt(param[1]); } } } cv.put(Profiles.LEVEL, level); cv.put(Profiles.PROGRESS, progress); cv.put(Profiles.TROPHIES_PLATINUM, trophiesPlat); cv.put(Profiles.TROPHIES_GOLD, trophiesGold); cv.put(Profiles.TROPHIES_SILVER, trophiesSilver); cv.put(Profiles.TROPHIES_BRONZE, trophiesBronze); String iconUrl = null; if ((m = PATTERN_AVATAR_CONTAINER.matcher(page)).find()) { if ((m = PATTERN_URL.matcher(m.group(1))).find()) iconUrl = m.group(1); } cv.put(Profiles.ICON_URL, iconUrl); if (App.getConfig().logToConsole()) started = displayTimeTaken("parseSummaryData processing", started); return cv; }
From source file:org.openrdf.http.client.SparqlSession.java
/** * Send the tuple query via HTTP and throws an exception in case anything * goes wrong, i.e. only for HTTP 200 the method returns without exception. * If HTTP status code is not equal to 200, the request is aborted, however * pooled connections are not released.//w w w . j av a2 s .c o m * * @param method * @throws RepositoryException * @throws HttpException * @throws IOException * @throws QueryInterruptedException * @throws MalformedQueryException */ private HttpResponse sendTupleQueryViaHttp(HttpUriRequest method, Set<TupleQueryResultFormat> tqrFormats) throws RepositoryException, IOException, QueryInterruptedException, MalformedQueryException { for (TupleQueryResultFormat format : tqrFormats) { // Determine a q-value that reflects the user specified preference int qValue = 10; if (preferredTQRFormat != null && !preferredTQRFormat.equals(format)) { // Prefer specified format over other formats qValue -= 2; } for (String mimeType : format.getMIMETypes()) { String acceptParam = mimeType; if (qValue < 10) { acceptParam += ";q=0." + qValue; } method.addHeader(ACCEPT_PARAM_NAME, acceptParam); } } try { return executeOK(method); } catch (RepositoryException e) { throw e; } catch (MalformedQueryException e) { throw e; } catch (QueryInterruptedException e) { throw e; } catch (OpenRDFException e) { throw new RepositoryException(e); } }
From source file:com.akop.bach.parser.PsnUsParser.java
protected void parseFriends(PsnAccount account) throws ParserException, IOException { synchronized (PsnUsParser.class) { String url = String.format(URL_FRIENDS, Math.random()); HttpUriRequest request = new HttpGet(url); request.addHeader("Referer", "http://us.playstation.com/myfriends/"); request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); String page = getResponse(request, null); ContentResolver cr = mContext.getContentResolver(); final long accountId = account.getId(); ContentValues cv;/* w ww.j a va 2 s .c o m*/ List<ContentValues> newCvs = new ArrayList<ContentValues>(100); int rowsInserted = 0; int rowsUpdated = 0; int rowsDeleted = 0; long updated = System.currentTimeMillis(); long started = updated; Matcher gameMatcher = PATTERN_FRIENDS.matcher(page); while (gameMatcher.find()) { String friendGt = htmlDecode(gameMatcher.group(1)); GamerProfileInfo gpi; try { gpi = parseGamerProfile(account, friendGt); } catch (IOException e) { if (App.getConfig().logToConsole()) App.logv("Friend " + friendGt + " threw an IOException"); // Update the DeleteMarker, so that the GT is not removed cv = new ContentValues(15); cv.put(Friends.DELETE_MARKER, updated); cr.update(Friends.CONTENT_URI, cv, Friends.ACCOUNT_ID + "=" + account.getId() + " AND " + Friends.ONLINE_ID + "=?", new String[] { friendGt }); continue; } catch (Exception e) { // The rest of the exceptions assume problems with Friend // and potentially remove him/her if (App.getConfig().logToConsole()) { App.logv("Friend " + friendGt + " threw an Exception"); e.printStackTrace(); } continue; } Cursor c = cr.query(Friends.CONTENT_URI, FRIEND_ID_PROJECTION, Friends.ACCOUNT_ID + "=" + account.getId() + " AND " + Friends.ONLINE_ID + "=?", new String[] { friendGt }, null); long friendId = -1; if (c != null) { try { if (c.moveToFirst()) friendId = c.getLong(0); } finally { c.close(); } } cv = new ContentValues(15); cv.put(Friends.ONLINE_ID, gpi.OnlineId); cv.put(Friends.ICON_URL, gpi.AvatarUrl); cv.put(Friends.LEVEL, gpi.Level); cv.put(Friends.PROGRESS, gpi.Progress); cv.put(Friends.ONLINE_STATUS, gpi.OnlineStatus); cv.put(Friends.TROPHIES_PLATINUM, gpi.PlatinumTrophies); cv.put(Friends.TROPHIES_GOLD, gpi.GoldTrophies); cv.put(Friends.TROPHIES_SILVER, gpi.SilverTrophies); cv.put(Friends.TROPHIES_BRONZE, gpi.BronzeTrophies); cv.put(Friends.PLAYING, gpi.Playing); cv.put(Friends.DELETE_MARKER, updated); cv.put(Friends.LAST_UPDATED, updated); if (friendId < 0) { // New cv.put(Friends.ACCOUNT_ID, accountId); newCvs.add(cv); } else { cr.update(ContentUris.withAppendedId(Friends.CONTENT_URI, friendId), cv, null, null); rowsUpdated++; } } // Remove friends rowsDeleted = cr.delete(Friends.CONTENT_URI, Friends.ACCOUNT_ID + "=" + accountId + " AND " + Friends.DELETE_MARKER + "!=" + updated, null); if (newCvs.size() > 0) { ContentValues[] cvs = new ContentValues[newCvs.size()]; newCvs.toArray(cvs); rowsInserted = cr.bulkInsert(Friends.CONTENT_URI, cvs); } account.refresh(Preferences.get(mContext)); account.setLastFriendUpdate(System.currentTimeMillis()); account.save(Preferences.get(mContext)); cr.notifyChange(Friends.CONTENT_URI, null); if (App.getConfig().logToConsole()) started = displayTimeTaken("Friend page processing [I:" + rowsInserted + ";U:" + rowsUpdated + ";D:" + rowsDeleted + "]", started); } }
From source file:me.code4fun.roboq.Request.java
protected HttpUriRequest createHttpRequest(int method, String url, Options opts) { String url1 = makeUrl(url, opts); // Create HTTP request HttpUriRequest httpReq; if (GET == method) { httpReq = new HttpGet(url1); } else if (POST == method) { httpReq = new HttpPost(url1); } else if (PUT == method) { httpReq = new HttpPut(url1); } else if (DELETE == method) { httpReq = new HttpDelete(url1); } else if (TRACE == method) { httpReq = new HttpTrace(url1); } else if (HEAD == method) { httpReq = new HttpHead(url1); } else if (OPTIONS == method) { httpReq = new HttpOptions(url1); } else {/*from ww w .j a v a 2s . co m*/ throw new IllegalStateException("Illegal HTTP method " + method); } // Set headers Map<String, Object> headers = opts.getHeaders(); for (Map.Entry<String, Object> entry : headers.entrySet()) { String k = entry.getKey(); Object v = entry.getValue(); if (v != null && v.getClass().isArray()) { int len = Array.getLength(v); for (int i = 0; i < len; i++) { Object v0 = Array.get(v, i); httpReq.addHeader(k, o2s(v0, "")); } } else if (v instanceof List) { for (Object v0 : (List) v) httpReq.addHeader(k, o2s(v0, "")); } else { httpReq.addHeader(k, o2s(v, "")); } } // set body if (httpReq instanceof HttpEntityEnclosingRequestBase) { ((HttpEntityEnclosingRequestBase) httpReq).setEntity(createRequestBody(method, url, opts)); } return httpReq; }
From source file:com.akop.bach.parser.PsnUsParser.java
protected ComparedTrophyInfo parseCompareTrophies(PsnAccount account, String friendId, String gameId) throws ParserException, IOException { String url = String.format(URL_COMPARE_TROPHIES, URLEncoder.encode(gameId, "UTF-8"), URLEncoder.encode(account.getScreenName(), "UTF-8"), URLEncoder.encode(friendId, "UTF-8")); HttpUriRequest request = new HttpGet(url); request.addHeader("Referer", String.format(URL_COMPARE_TROPHIES_REFERER, URLEncoder.encode(friendId, "UTF-8"))); // Fetch the "main" page String page = getResponse(request, null); ComparedTrophyInfo cti = new ComparedTrophyInfo(mContext.getContentResolver()); Map<Integer, Object> trophy; ArrayList<Map<Integer, Object>> trophies = new ArrayList<Map<Integer, Object>>(); Map<String, Map<Integer, Object>> trophyMap = new HashMap<String, Map<Integer, Object>>(); Matcher m;/*from w w w . java2s .c o m*/ if (!(m = PATTERN_COMPARE_TROPHIES_TITLE_ID.matcher(page)).find()) { if (App.getConfig().logToConsole()) App.logv("No title ID for " + gameId); return cti; } String nullUnlockString = PSN.getShortTrophyUnlockString(mContext, 0); String titleId = m.group(1); long started = System.currentTimeMillis(); Matcher matcher = PATTERN_COMPARE_TROPHIES.matcher(page); for (; matcher.find();) { String trophyId = matcher.group(1); String group = matcher.group(3); trophy = new HashMap<Integer, Object>(); if ((m = PATTERN_COMPARE_TROPHIES_TITLE.matcher(group)).find()) { trophy.put(ComparedTrophyCursor.COLUMN_TITLE, htmlDecode(m.group(1).trim())); if ((m = PATTERN_TROPHY_DESCRIPTION.matcher(group)).find()) trophy.put(ComparedTrophyCursor.COLUMN_DESCRIPTION, htmlDecode(m.group(1).trim())); else trophy.put(ComparedTrophyCursor.COLUMN_DESCRIPTION, null); } else { trophy.put(ComparedTrophyCursor.COLUMN_TITLE, mContext.getString(R.string.secret_trophy)); trophy.put(ComparedTrophyCursor.COLUMN_DESCRIPTION, mContext.getString(R.string.this_is_a_secret_trophy)); } if ((m = PATTERN_TROPHY_ICON.matcher(group)).find()) trophy.put(ComparedTrophyCursor.COLUMN_ICON_URL, getAvatarImage(m.group(1))); else trophy.put(ComparedTrophyCursor.COLUMN_ICON_URL, null); if ((m = PATTERN_TROPHY_TYPE.matcher(group)).find()) { String trophyType = m.group(1).toUpperCase(); if (trophyType.equals("BRONZE")) trophy.put(ComparedTrophyCursor.COLUMN_TYPE, PSN.TROPHY_BRONZE); else if (trophyType.equals("SILVER")) trophy.put(ComparedTrophyCursor.COLUMN_TYPE, PSN.TROPHY_SILVER); else if (trophyType.equals("GOLD")) trophy.put(ComparedTrophyCursor.COLUMN_TYPE, PSN.TROPHY_GOLD); else if (trophyType.equals("PLATINUM")) trophy.put(ComparedTrophyCursor.COLUMN_TYPE, PSN.TROPHY_PLATINUM); else if (trophyType.equals("HIDDEN")) trophy.put(ComparedTrophyCursor.COLUMN_TYPE, PSN.TROPHY_SECRET); } trophy.put(ComparedTrophyCursor.COLUMN_IS_LOCKED, true); trophy.put(ComparedTrophyCursor.COLUMN_SELF_EARNED, nullUnlockString); trophy.put(ComparedTrophyCursor.COLUMN_OPP_EARNED, nullUnlockString); trophyMap.put(trophyId, trophy); trophies.add(trophy); } if (App.getConfig().logToConsole()) started = displayTimeTaken("parseCompareTrophies/processing", started); JSONArray array; JSONObject json; // Run the compare requests url = String.format(URL_COMPARE_TROPHIES_DETAIL, URLEncoder.encode(titleId, "UTF-8"), URLEncoder.encode(account.getScreenName(), "UTF-8")); page = getResponse(url, true); json = getJSONObject(page); if ((array = json.optJSONArray("trophyList")) != null) { int n = array.length(); for (int i = 0; i < n; i++) { if ((json = array.optJSONObject(i)) != null) { String trophyId = json.optString("id"); if (trophyId != null && trophyMap.containsKey(trophyId)) { long earned; String dateTime = json.optString("stampDate") + " " + json.optString("stampTime"); try { earned = COMPARE_TROPHY_DATE_FORMAT.parse(dateTime).getTime(); } catch (ParseException e) { if (App.getConfig().logToConsole()) e.printStackTrace(); continue; } trophyMap.get(trophyId).put(ComparedTrophyCursor.COLUMN_IS_LOCKED, false); trophyMap.get(trophyId).put(ComparedTrophyCursor.COLUMN_SELF_EARNED, PSN.getShortTrophyUnlockString(mContext, earned)); } } } } url = String.format(URL_COMPARE_TROPHIES_DETAIL, URLEncoder.encode(titleId, "UTF-8"), URLEncoder.encode(friendId, "UTF-8")); page = getResponse(url, true); json = getJSONObject(page); if ((array = json.optJSONArray("trophyList")) != null) { int n = array.length(); for (int i = 0; i < n; i++) { if ((json = array.optJSONObject(i)) != null) { String trophyId = json.optString("id"); if (trophyId != null && trophyMap.containsKey(trophyId)) { long earned; String dateTime = json.optString("stampDate") + " " + json.optString("stampTime"); try { earned = COMPARE_TROPHY_DATE_FORMAT.parse(dateTime).getTime(); } catch (ParseException e) { if (App.getConfig().logToConsole()) e.printStackTrace(); continue; } trophyMap.get(trophyId).put(ComparedTrophyCursor.COLUMN_OPP_EARNED, PSN.getShortTrophyUnlockString(mContext, earned)); } } } } for (Map<Integer, Object> t : trophies) { cti.cursor.addItem((String) t.get(ComparedTrophyCursor.COLUMN_TITLE), (String) t.get(ComparedTrophyCursor.COLUMN_DESCRIPTION), (String) t.get(ComparedTrophyCursor.COLUMN_ICON_URL), (Integer) t.get(ComparedTrophyCursor.COLUMN_TYPE), (Integer) t.get(ComparedTrophyCursor.COLUMN_TYPE) == PSN.TROPHY_SECRET, (Boolean) t.get(ComparedTrophyCursor.COLUMN_IS_LOCKED), (String) t.get(ComparedTrophyCursor.COLUMN_SELF_EARNED), (String) t.get(ComparedTrophyCursor.COLUMN_OPP_EARNED)); } return cti; }
From source file:biocode.fims.ezid.EzidService.java
/** * Send an HTTP request to the EZID service with a request body (for POST and PUT requests). * * @param requestType the type of the service as an integer * @param uri endpoint to be accessed in the request * @param requestBody the String body to be encoded into the body of the request * * @return byte[] containing the response body *//*from ww w .j a v a 2s.c om*/ private byte[] sendRequest(int requestType, String uri, String requestBody) throws EzidException { HttpUriRequest request = null; log.debug("Trying uri: " + uri); System.out.println("uri = " + uri); switch (requestType) { case GET: request = new HttpGet(uri); break; case PUT: request = new HttpPut(uri); if (requestBody != null && requestBody.length() > 0) { try { StringEntity myEntity = new StringEntity(requestBody, "UTF-8"); ((HttpPut) request).setEntity(myEntity); } catch (UnsupportedEncodingException e) { throw new EzidException(e); } } break; case POST: request = new HttpPost(uri); if (requestBody != null && requestBody.length() > 0) { try { System.out.println("requestBody = " + requestBody); StringEntity myEntity = new StringEntity(requestBody, "UTF-8"); ((HttpPost) request).setEntity(myEntity); } catch (UnsupportedEncodingException e) { throw new EzidException(e); } } break; case DELETE: request = new HttpDelete(uri); break; default: throw new EzidException("Unrecognized HTTP method requested."); } request.addHeader("Accept", "text/plain"); /* HACK -- re-authorize on the fly as this was getting dropped on SI server*/ /*String auth = this.username + ":" + this.password; String encodedAuth = org.apache.commons.codec.binary.Base64.encodeBase64String(auth.getBytes()); request.addHeader("Authorization", "Basic " + encodedAuth); */ ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() { public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toByteArray(entity); } else { return null; } } }; byte[] body = null; try { body = httpClient.execute(request, handler); } catch (ClientProtocolException e) { throw new EzidException(e); } catch (IOException e) { throw new EzidException(e); } return body; }
From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java
private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException { if (AGENT != null) { hr.addHeader("User-Agent", AGENT); }//from w ww . j av a 2 s . c om if (headers != null) { for (String name : headers.keySet()) { hr.addHeader(name, headers.get(name)); } } if (GZIP && ((headers == null) || !headers.containsKey("Accept-Encoding"))) { hr.addHeader("Accept-Encoding", "gzip"); } String cookie = makeCookie(); if (cookie != null) { hr.addHeader("Cookie", cookie); } if (ah != null) { ah.applyToken(this, hr); } DefaultHttpClient client = getClient(); HttpParams hp = hr.getParams(); if (proxy != null) { hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } if (timeout > 0) { hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout); hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout); } HttpContext context = new BasicHttpContext(); // CookieStore cookieStore = new BasicCookieStore(); // context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); request = hr; if (abort) { throw new IOException("Aborted"); } HttpResponse response = null; try { //response = client.execute(hr, context); response = execute(hr, client, context); getCookie(client); } catch (HttpHostConnectException e) { //if proxy is used, automatically retry without proxy if (proxy != null) { AQUtility.debug("proxy failed, retrying without proxy"); hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, null); //response = client.execute(hr, context); response = execute(hr, client, context); } else { throw e; } } byte[] data = null; String redirect = url; int code = response.getStatusLine().getStatusCode(); String message = response.getStatusLine().getReasonPhrase(); String error = null; HttpEntity entity = response.getEntity(); File file = null; if ((code < 200) || (code >= 300)) { InputStream is = null; try { if (entity != null) { is = entity.getContent(); byte[] s = toData(getEncoding(entity), is); error = new String(s, "UTF-8"); AQUtility.debug("error", error); } } catch (Exception e) { AQUtility.debug(e); } finally { AQUtility.close(is); } } else { HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); redirect = currentHost.toURI() + currentReq.getURI(); int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength())); OutputStream os = null; InputStream is = null; try { file = getPreFile(); if (file == null) { os = new PredefinedBAOS(size); } else { file.createNewFile(); os = new BufferedOutputStream(new FileOutputStream(file)); } is = entity.getContent(); if ("gzip".equalsIgnoreCase(getEncoding(entity))) { is = new GZIPInputStream(is); } copy(is, os, (int) entity.getContentLength()); os.flush(); if (file == null) { data = ((PredefinedBAOS) os).toByteArray(); } else { if (!file.exists() || (file.length() == 0)) { file = null; } } } finally { AQUtility.close(is); AQUtility.close(os); } } AQUtility.debug("response", code); if (data != null) { AQUtility.debug(data.length, url); } status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file) .client(client).context(context).headers(response.getAllHeaders()); }