public String executeHttpGet(String URL) throws Exception { BufferedReader in = null; try { HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android"); HttpGet request = new HttpGet(); request.setHeader("Content-Type", "text/plain; charset=utf-8"); request.setURI(new URI(URL)); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String page = sb.toString(); // System.out.println(page); return page; } finally { if (in != null) { try { in.close(); } catch (IOException e) { Log.d("BBB", e.toString()); } } } }
@Override protected String doInBackground(String... url) { if (allPhoneContacts != null) { allPhoneContacts.clear(); } if (syncedContacts != null) { syncedContacts.clear(); } String resp = ""; Header[] responseHeaders = null; HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLSEC); HttpGet request = new HttpGet(url[0]); MyHttpClient Client = LogonClass.Client; Client.putContext(context); try { request.setHeader("syncstatus", "True"); HttpResponse response = Client.execute(request); resp = EntityUtils.toString(response.getEntity()); responseHeaders = response.getAllHeaders(); } catch (Exception e) { resp = "none is righteous"; } Log.v(TAG, "response is " + resp); return resp; }
private String doGet(String url) { String responseStr = ""; try { HttpGet httpRequest = new HttpGet(url); HttpParams params = new BasicHttpParams(); ConnManagerParams.setTimeout(params, 1000); HttpConnectionParams.setConnectionTimeout(params, 3000); HttpConnectionParams.setSoTimeout(params, 5000); httpRequest.setParams(params); HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest); final int ret = httpResponse.getStatusLine().getStatusCode(); if (ret == HttpStatus.SC_OK) { responseStr = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8); } else { responseStr = "-1"; } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return responseStr; }
public static List<RoleRepresentation> getRealmRoles(HttpServletRequest req) throws Failure { KeycloakSecurityContext session = (KeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName()); HttpClient client = new HttpClientBuilder().disableTrustManager().build(); try { HttpGet get = new HttpGet( AdapterUtils.getOriginForRestCalls(req.getRequestURL().toString(), session) + "/auth/admin/realms/demo/roles"); get.addHeader("Authorization", "Bearer " + session.getTokenString()); try { HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() != 200) { throw new Failure(response.getStatusLine().getStatusCode()); } HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); try { return JsonSerialization.readValue(is, TypedList.class); } finally { is.close(); } } catch (IOException e) { throw new RuntimeException(e); } } finally { client.getConnectionManager().shutdown(); } }
/** * Fetches user's e-mail - only public for testing. * * @param allToks OAuth tokens. * @param httpClient The HTTP client. */ public int fetchEmail(final Map<String, String> allToks, final HttpClient httpClient) { final String endpoint = "https://www.googleapis.com/oauth2/v1/userinfo"; final String accessToken = allToks.get("access_token"); final HttpGet get = new HttpGet(endpoint); get.setHeader(HttpHeaders.Names.AUTHORIZATION, "Bearer " + accessToken); try { log.debug("About to execute get!"); final HttpResponse response = httpClient.execute(get); final StatusLine line = response.getStatusLine(); log.debug("Got response status: {}", line); final HttpEntity entity = response.getEntity(); final String body = IOUtils.toString(entity.getContent(), "UTF-8"); EntityUtils.consume(entity); log.debug("GOT RESPONSE BODY FOR EMAIL:\n" + body); final int code = line.getStatusCode(); if (code < 200 || code > 299) { log.error("OAuth error?\n" + line); return code; } final Profile profile = JsonUtils.OBJECT_MAPPER.readValue(body, Profile.class); this.model.setProfile(profile); Events.sync(SyncPath.PROFILE, profile); // final String email = profile.getEmail(); // this.model.getSettings().setEmail(email); return code; } catch (final IOException e) { log.warn("Could not connect to Google?", e); } finally { get.reset(); } return -1; }
private static Bitmap getCaptchaImage(HttpClient client, String captchaId) throws ClientProtocolException, IOException { final HttpGet request = new HttpGet(String.format(CAPTCHA_IMAGE, captchaId)); request.addHeader("User-Agent", USER_AGENT); request.addHeader("Referer", REFERER); request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); final HttpResponse response = client.execute(request); final HttpEntity entity = response.getEntity(); final InputStream in = entity.getContent(); int next; final ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((next = in.read()) != -1) { bos.write(next); } bos.flush(); byte[] result = bos.toByteArray(); bos.close(); entity.consumeContent(); return BitmapFactory.decodeByteArray(result, 0, result.length); }
@Override public List<Entity> annotateEntity(Entity entity) { HttpGet httpGet = new HttpGet(getServiceUri(entity)); Entity resultEntity = new MapEntity(); if (!annotatedInput.contains(entity.get(UNIPROT_ID))) { annotatedInput.add(entity.get(UNIPROT_ID)); try { HttpResponse response = httpClient.execute(httpGet); BufferedReader br = new BufferedReader( new InputStreamReader( (response.getEntity().getContent()), Charset.forName("UTF-8"))); String output; StringBuilder result = new StringBuilder(); while ((output = br.readLine()) != null) { result.append(output); } resultEntity = parseResult(entity, result.toString()); } catch (Exception e) { httpGet.abort(); // TODO: how to handle exceptions at this point throw new RuntimeException(e); } } return Collections.singletonList(resultEntity); }
public String call(String url, Map<String, String> fields) { // create an HTTP request to a protected resource HttpGet request = new HttpGet(endpoint); HttpParams p = new BasicHttpParams(); for (Entry<String, String> en : fields.entrySet()) { p.setParameter(en.getKey(), en.getValue()); } request.setParams(p); // sign the request try { consumer2.sign(request); } catch (OAuthMessageSignerException e) { e.printStackTrace(); } catch (OAuthExpectationFailedException e) { e.printStackTrace(); } // send the request HttpClient httpClient = new DefaultHttpClient(); try { HttpResponse response = httpClient.execute(request); return convertStreamToString(response.getEntity().getContent()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
/** * This method retrieves data using HTTP or HTTPS protocol and 'get' method. * * @param url * @return */ protected byte[] httpGet(String url) { HttpGet httpRequest = null; HttpResponse httpResponse = null; try { final URI uri = URI.create(url.trim()); httpRequest = new HttpGet(uri); if (contentType != null) { httpRequest.setHeader(CONTENT_TYPE, contentType); } httpResponse = getHttpResponse(httpRequest, url); final byte[] returnedBytes = readHttpResponse(url, httpResponse); return returnedBytes; } finally { if (httpRequest != null) { httpRequest.releaseConnection(); } if (httpResponse != null) { EntityUtils.consumeQuietly(httpResponse.getEntity()); } } }
public static Bitmap downloadBitmap(String url) { DefaultHttpClient client = getDefaultHttpClient(null); final HttpGet getRequest = new HttpGet(url); try { HttpResponse response = client.execute(getRequest); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { return null; } final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = null; try { inputStream = entity.getContent(); final Bitmap bitmap = BitmapFactory.decodeStream(inputStream); return bitmap; } finally { if (inputStream != null) { inputStream.close(); } entity.consumeContent(); } } } catch (Exception e) { getRequest.abort(); } finally { if (client != null) { client.getConnectionManager().shutdown(); } } return null; }
@Override protected Drawable doInBackground(String... param) { Drawable thumbnail = null; try { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(); httpGet.setURI(new URI(param[0])); httpGet.setHeader("Accept", "image/jpeg"); HttpResponse response = httpClient.execute(httpGet); InputStream inputStream = response.getEntity().getContent(); thumbnail = Drawable.createFromStream(inputStream, "src name"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } return thumbnail; }
private void requestReadingList() throws HttpException, IOException { if (!this.isRight()) return; int originalSize = 0; if (feed != null) { items = feed.getItems(); originalSize = items.size(); } String url = "https://www.google.com/reader/atom/user/-/state/com.google/reading-list?n=" + String.valueOf(pagenumber * everypage); HttpClient httpclient = new DefaultHttpClient(); getreadinglistmethod = new HttpGet(url); getreadinglistmethod.setHeader("Authorization", "GoogleLogin auth=" + auth); getreadinglistmethod.setHeader("Cookie", "SID=" + sid); getreadinglistmethod.setHeader("accept-encoding", "gzip, deflate"); HttpResponse response = null; response = httpclient.execute(getreadinglistmethod); int result = response.getStatusLine().getStatusCode(); // Log.d("GOOGLE_READER", "load result"+result); if (result >= 200 && result <= 299) { RssParser rp = new RssParser(response.getEntity().getContent()); // //System.out.println("++++++++++"); // //System.out.println((rp != null ? 1 : 0)); rp.parse(); feed = rp.getFeed(); try { items = feed.getItems(); if (items.size() == originalSize) { throw new NoMoreStatusException(); } } catch (Exception e) { e.printStackTrace(); throw new NoNetworkException(e); } greaderlistItems = new ArrayList<GreaderListItem>(); for (RssParser.Item item : items) { { GreaderListItem greaderlistItem = new GreaderListItem(); greaderlistItem.setId(item.id); greaderlistItem.setTitle(item.title); greaderlistItem.setLink(item.link); greaderlistItem.setAuthor(item.author); greaderlistItems.add(greaderlistItem); } } fromindex = (pagenumber - 1) * everypage; pagenumber += 1; lastModified = new Date(); // this.getreadingliststring=getreadinglistmethod.getResponseBodyAsString(); } else { throw new NoNetworkException(); } releaseReadingList(getreadinglistmethod); }
// taglist private StringBuilder requestList(String url) throws HttpException, IOException { HttpClient httpclient = new DefaultHttpClient(); HttpGet get = new HttpGet(url); get.setHeader("Authorization", "GoogleLogin auth=" + auth); get.setHeader("Cookie", "SID=" + sid); get.setHeader("accept-encoding", "gzip, deflate"); HttpResponse response = null; response = httpclient.execute(get); int result = response.getStatusLine().getStatusCode(); StringBuilder requestListSB; if (result == 200) { // //System.out.println(get.getResponseBodyAsString()); requestListSB = new StringBuilder(EntityUtils.toString(response.getEntity())); } else { //// System.out.println("xxx:" + String.valueOf(result)); requestListSB = null; } get.abort(); httpclient.getConnectionManager().shutdown(); httpclient = null; return requestListSB; }
public void requestToken() throws ParseException, HttpException, IOException { if (!this.isGetSidAndAuth) return; String url = "https://www.google.com/reader/api/0/token?client=scroll&ck="; // HttpClient httpclient = new DefaultHttpClient(); DefaultHttpClient httpclient = new DefaultHttpClient(); String timestap = String.valueOf(getTimestamp()); HttpGet get = new HttpGet(url + timestap); get.setHeader("Authorization", "GoogleLogin auth=" + auth); get.setHeader("Cookie", "SID=" + sid); HttpResponse response = null; response = httpclient.execute(get); int result = response.getStatusLine().getStatusCode(); ////// System.out.println(result); if (result == 200) { // this.token = get.getResponseBodyAsString().substring(2); //// System.out.println("2222222222222"); this.token = EntityUtils.toString(response.getEntity()).substring(2); //// System.out.println(this.token); } // ////System.out.println(this.token); get.abort(); httpclient.getConnectionManager().shutdown(); httpclient = null; }
@Override protected Object doInBackground(Object... params) { // TODO Auto-generated method stub try { HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); String website = "http://myflickpicks.net/php/db/deleteusermovie.php?UserID=" + currentUser.getId() + "&MovieTitle=" + params[0].toString().replace(" ", "%20"); HttpGet httpGet = new HttpGet(website); httpGet.setHeader("accept", "application/json"); HttpResponse response = httpClient.execute(httpGet, localContext); // Toast.makeText(getActivity().getApplicationContext(), "Adding", // Toast.LENGTH_LONG).show(); // For example Log.v("MyDebug", "Door 1"); Log.v("MyDebug", currentUser.getId()); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.v("MyDebug", "Door 2"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); Log.v("MyDebug", "Door 3"); } return null; }
public static HttpHeaderInfo getHttpHeader(String url, Map<Object, Object> headers) throws ClientProtocolException, IOException { HttpGet httpGet = new HttpGet(url); if (headers != null) { for (Map.Entry<Object, Object> entry : headers.entrySet()) { httpGet.addHeader(entry.getKey() + "", entry.getValue() + ""); } } CloseableHttpResponse response = minHttpclient.execute(httpGet); try { response.close(); HttpHeaderInfo headerInfo = new HttpHeaderInfo(); headerInfo.setStatus(response.getStatusLine().getStatusCode()); headerInfo.setReasonPhrase(response.getStatusLine().getReasonPhrase()); Header[] allHeaders = response.getAllHeaders(); if (allHeaders != null) { Map<String, Object> headerMap = new HashMap<String, Object>(); for (Header header : allHeaders) { headerMap.put(header.getName(), header.getValue()); } headerInfo.setHeaders(headerMap); } return headerInfo; } finally { response.close(); } }
static void testBasicAuth() throws ClientProtocolException, IOException { HttpHost targetHost = new HttpHost("localhost", 8080, "http"); DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient .getCredentialsProvider() .setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("newuser", "tomcat")); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context BasicHttpContext localcontext = new BasicHttpContext(); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); HttpGet httpget = new HttpGet("/simpleweb/protected"); System.out.println(httpget.getURI()); HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine().getStatusCode()); String charset = HttpclientTutorial.getResponseCharset(response); HttpclientTutorial.output(entity, charset); EntityUtils.consume(entity); }
/** * Performs an HTTP GET request to the specified url. * * @param url The web address to post the request to * @return The result of the request * @throws Exception */ public static String executeHttpGet(String url) throws Exception { BufferedReader in = null; try { // HttpClient httpclient = new DefaultHttpClient(); // HttpPost httppost = new HttpPost("http://example.com/your_file.php"); // ResponseHandler<String> responseHandler = new BasicResponseHandler(); // String responseBody = httpclient.execute(httppost, responseHandler); HttpClient client = getHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(url)); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String result = sb.toString(); return result; } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } }
public void testMojoExecution() throws Exception { assertNotNull(mojo); mojo.execute(); HttpClient client = HttpClientBuilder.create().build(); HttpGet get = new HttpGet("http://localhost:" + elasticsearchNode.getHttpPort()); final int connectionTimeout = 500; // millis RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(connectionTimeout) .setConnectTimeout(connectionTimeout) .setSocketTimeout(connectionTimeout) .build(); get.setConfig(requestConfig); try { client.execute(get); fail("The ES cluster should have been down by now"); } catch (HttpHostConnectException | ConnectTimeoutException expected) { } assertTrue(elasticsearchNode.isClosed()); }
/** * Wrapper around a HTTP GET to a REST service * * @param url * @return JSONObject */ static JSONObject performHTTPGet(String url) throws IOException, JSONException { HttpClient httpClient = new DefaultHttpClient(); String encoding = new String( org.apache.commons.codec.binary.Base64.encodeBase64( org.apache.commons.codec.binary.StringUtils.getBytesUtf8( props.getProperty(StringConstants.COMMANDER_USER) + ":" + props.getProperty(StringConstants.COMMANDER_PASSWORD)))); try { HttpGet httpGetRequest = new HttpGet(url); httpGetRequest.setHeader("Authorization", "Basic " + encoding); HttpResponse httpResponse = httpClient.execute(httpGetRequest); if (httpResponse.getStatusLine().getStatusCode() >= 400) { throw new RuntimeException( "HTTP GET failed with " + httpResponse.getStatusLine().getStatusCode() + "-" + httpResponse.getStatusLine().getReasonPhrase()); } return new JSONObject(EntityUtils.toString(httpResponse.getEntity())); } finally { httpClient.getConnectionManager().shutdown(); } }
@Test public void testReqriteHostHeader() throws Exception { setProxyHandler(true, false); TestHttpClient client = new TestHttpClient(); try { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/x-forwarded"); get.addHeader(Headers.X_FORWARDED_FOR.toString(), "50.168.245.32"); HttpResponse result = client.execute(get); Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); Assert.assertEquals( port, Integer.parseInt(result.getFirstHeader(Headers.X_FORWARDED_PORT.toString()).getValue())); Assert.assertEquals( "http", result.getFirstHeader(Headers.X_FORWARDED_PROTO.toString()).getValue()); Assert.assertEquals( String.format("localhost:%d", port), result.getFirstHeader(Headers.X_FORWARDED_HOST.toString()).getValue()); Assert.assertEquals( DefaultServer.getDefaultServerAddress().getAddress().getHostAddress(), result.getFirstHeader(Headers.X_FORWARDED_FOR.toString()).getValue()); } finally { client.getConnectionManager().shutdown(); } }
@Test public void testKeepAlive() throws Exception { String url = httpServerUrl + "4ae3851817194e2596cf1b7103603ef8/pin/a14"; HttpPut request = new HttpPut(url); request.setHeader("Connection", "keep-alive"); HttpGet getRequest = new HttpGet(url); getRequest.setHeader("Connection", "keep-alive"); for (int i = 0; i < 100; i++) { request.setEntity(new StringEntity("[\"" + i + "\"]", ContentType.APPLICATION_JSON)); try (CloseableHttpResponse response = httpclient.execute(request)) { assertEquals(200, response.getStatusLine().getStatusCode()); EntityUtils.consume(response.getEntity()); } try (CloseableHttpResponse response2 = httpclient.execute(getRequest)) { assertEquals(200, response2.getStatusLine().getStatusCode()); List<String> values = consumeJsonPinValues(response2); assertEquals(1, values.size()); assertEquals(String.valueOf(i), values.get(0)); } } }
public HttpGet prepareHttpGet(URI uri) { HttpGet httpget = new HttpGet(uri); httpget.addHeader("content-type", this.configuration.getContentType()); if (!Strings.isNullOrEmpty(authHeader)) httpget.addHeader("Authorization", String.format("Basic %s", authHeader)); return httpget; }
/** * Get请求 * * @param url * @param params * @return */ public static String get(String url, List<NameValuePair> params) { String body = null; try { // Get请求 HttpGet httpget = new HttpGet(url); // 设置参数 String str = EntityUtils.toString(new UrlEncodedFormEntity(params)); httpget.setURI(new URI(httpget.getURI().toString() + "?" + str)); // 发送请求 HttpResponse httpresponse = httpClient.execute(httpget); // 获取返回数据 HttpEntity entity = httpresponse.getEntity(); body = EntityUtils.toString(entity); if (entity != null) { entity.consumeContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } return body; }
@Test public final void givenCustomHeaderIsSet_whenSendingRequest_thenNoExceptions() throws ClientProtocolException, IOException { final HttpGet request = new HttpGet(SAMPLE_URL); request.addHeader(HttpHeaders.ACCEPT, "application/xml"); response = instance.execute(request); }
/** * Fill an http get request with the header information. * * @param get An http get request */ public void fill(HttpGet get) { get.addHeader("User-Agent", user_agent); get.addHeader("Accept", accept); get.addHeader("Accept-Language", accept_language); get.addHeader("Accept-Encoding", accept_encoding); get.addHeader("Connection", connection); }
public String Coment(String membre, String contenu, int lieu, float rate) throws Exception { String link = "http:" + Utilisateur.ip + "/geekAdvisorApi/avisApi.php?membre=" + URLEncoder.encode(membre) + "&contenu=" + URLEncoder.encode(contenu) + "&lieu=" + lieu + "&rate=" + rate + ""; URL url = new URL(link); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(link)); HttpResponse response = client.execute(request); BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; while ((line = in.readLine()) != null) { sb.append(line); break; } // jObject = new JSONObject(sb.toString()); in.close(); return sb.toString(); }
/*public static double getTescoTotal(String barcode) throws JSONException { double parsedvalue= JsonObject.getTescoProductValue(barcode); //int i= Integer.parseInt(parsedvalue); int total = 0; while(parsedvalue!=0) { total+=parsedvalue; } return total; }*/ public static String getTescoProductName(String barcode) throws JSONException { String key = "empty"; key = login(); String URL = startURL + key + "&SEARCHTEXT=" + barcode; // InputStream is=null; HttpClient httpclient = new DefaultHttpClient(); HttpGet request = new HttpGet(URL); request.addHeader("deviceId", deviceId); ResponseHandler<String> handler = new BasicResponseHandler(); try { result = httpclient.execute(request, handler); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } jObject = new JSONObject(result); JSONArray productinfo = jObject.getJSONArray("Products"); String name = null; for (int i = 0; i < productinfo.length(); i++) { name = productinfo.getJSONObject(i).getString("Name").toString(); } return name; }
/** * Get the user preferences from the GPII * * @param user * @return * @throws Exception */ private String getPreferencesFromServer(EasitAccount user) throws Exception { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet( environment.getProperty("flowManager.url") + environment.getProperty("flowManager.preferences")); // add the access token to the request header request.addHeader("Authorization", "Bearer " + user.getAccessToken()); HttpResponse response = client.execute(request); // NOT Correct answer if (response.getStatusLine().getStatusCode() != 200) { throw new Exception("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } // Correct answer BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } logger.info("User preferences:" + result); return result.toString(); }
/** * Get方法传送消息 * * @param url 连接的URL * @param queryString 请求参数串 * @return 服务器返回的信息 * @throws Exception */ public String httpGet(String url, String queryString) throws Exception { String responseData = null; if (queryString != null && !queryString.equals("")) { url += "?" + queryString; } RequestBuilder requestBuilder = RequestBuilder.get().setUri(url); log.info("QHttpClient httpGet [1] url = " + url); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(new Integer(CONNECTION_TIMEOUT)) .setCookieSpec(CookieSpecs.IGNORE_COOKIES) .build(); requestBuilder.setConfig(requestConfig); HttpResponse response; HttpGet httpGet = (HttpGet) requestBuilder.build(); response = httpClient.execute(httpGet); try { log.info("QHttpClient httpGet [2] StatusLine : " + response.getStatusLine()); responseData = EntityUtils.toString(response.getEntity()); log.info("QHttpClient httpGet [3] Response = " + responseData); } catch (Exception e) { e.printStackTrace(); } finally { httpGet.abort(); } return responseData; }