List of usage examples for org.apache.http.impl.client DefaultHttpClient DefaultHttpClient
public DefaultHttpClient()
From source file:HttpUtils.java
public static void testUrl(String url) throws ClientProtocolException, IOException { HttpHead head = new HttpHead(url); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(head); StatusLine status = response.getStatusLine(); if (status.getStatusCode() == 404) { throw new FileNotFoundException(); }/*from w w w . ja v a2 s .c o m*/ if (status.getStatusCode() != 200) { throw new RuntimeException( "Could not get URL: " + status.getStatusCode() + ": " + status.getReasonPhrase()); } }
From source file:com.mycompany.trader.HTTPTransport.java
public static String sendData(HttpPost data, String header) throws Exception { try {/*from www .j a va 2s . c om*/ DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(data); StringBuilder buffer = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; while ((output = br.readLine()) != null) { buffer.append(output); } System.out.println("response from server:"); System.out.println(buffer.toString()); if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 201) { buffer.append("error_code:" + response.getStatusLine().getStatusCode()); } httpClient.getConnectionManager().shutdown(); return buffer.toString(); } catch (Exception e) { //e.printStackTrace(); throw new Exception("server returned code: " + e.getMessage()); } }
From source file:org.opf_labs.fmts.fidget.droid.PRONOMSigGenerator.java
/** * @param sigdef/*from ww w.j a v a2s . c o m*/ */ public static void generatePRONOMSigFile(SigDefSubmission sigdef) { DefaultHttpClient httpclient = new DefaultHttpClient(); try { HttpPost httpost = new HttpPost(SERVICE_URL); httpost.setEntity(new UrlEncodedFormEntity(createNameValuePairs(sigdef), Consts.UTF_8)); HttpResponse response = httpclient.execute(httpost); HttpEntity entity = response.getEntity(); // Print out: IOUtils.copy(entity.getContent(), System.out); // Finish up: EntityUtils.consume(entity); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:com.android.feedmeandroid.HTTPClient.java
public static ArrayList<JSONObject> SendHttpPost(String URL, JSONObject jsonObjSend) { try {//from w w w.ja v a2 s . c o m ArrayList<JSONObject> retArray = new ArrayList<JSONObject>(); DefaultHttpClient httpclient = new DefaultHttpClient(); HttpPost httpPostRequest = new HttpPost(URL); StringEntity se; se = new StringEntity(jsonObjSend.toString()); // Set HTTP parameters httpPostRequest.setEntity(se); httpPostRequest.setHeader("Accepts", "application/json"); httpPostRequest.setHeader("Content-Type", "application/json"); // httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set // this parameter if you would like to use gzip compression long t = System.currentTimeMillis(); HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest); Log.v(TAG, "HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]"); // Get hold of the response entity (-> the data): HttpEntity entity = response.getEntity(); if (entity != null) { // Read the content stream InputStream instream = entity.getContent(); Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { instream = new GZIPInputStream(instream); } // convert content stream to a String String resultString = convertStreamToString(instream); Log.i(TAG, resultString); instream.close(); resultString = resultString.substring(1, resultString.length() - 2); // remove wrapping "[" and // "]" String[] results = resultString.split("\\},\\{"); for (int i = 0; i < results.length; i++) { JSONObject jsonObjRecv; String res = results[i]; // Transform the String into a JSONObject if (i == 0 && results.length > 1) { jsonObjRecv = new JSONObject(res + "}"); } else if (i == results.length - 1 && results.length > 1) { jsonObjRecv = new JSONObject("{" + res); } else { jsonObjRecv = new JSONObject("{" + res + "}"); } retArray.add(jsonObjRecv); // Raw DEBUG output of our received JSON object: Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>"); } return retArray; } } catch (Exception e) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. e.printStackTrace(); } return null; }
From source file:info.smartkit.hairy_batman.demo.MoniterWechatBrowser.java
/** * ?URLhtml?// w ww .jav a2 s . com */ @SuppressWarnings("deprecation") public static String getHttpClientHtml(String url, String code, String userAgent) { String html = null; @SuppressWarnings("deprecation") DefaultHttpClient httpClient = new DefaultHttpClient();// httpClient HttpGet httpget = new HttpGet(url);// get?URL // Pause for 4 seconds try { Thread.sleep(5000); } catch (InterruptedException e1) { e1.printStackTrace(); System.out.println(e1.toString()); } // httpget.setHeader("User-Agent", userAgent); try { // responce HttpResponse responce = httpClient.execute(httpget); // ? int returnCode = responce.getStatusLine().getStatusCode(); // 200? ? if (returnCode == HttpStatus.SC_OK) { // HttpEntity entity = responce.getEntity(); if (entity != null) { html = new String(EntityUtils.toString(entity));// html?? } } } catch (Exception e) { System.out.println(""); e.printStackTrace(); } finally { httpClient.getConnectionManager().shutdown(); } return html; }
From source file:org.jboss.demo.loanmanagement.client.RestCommandRunner.java
/** * @param restCommand the command to execute (cannot be <code>null</code>) * @return the response as a JSON object (never <code>null</code>) * @throws Exception if there are problems executing the command */// w w w .j a v a2s . c o m public static JSONObject run(final Command restCommand) throws Exception { final HttpGet httpGet = new HttpGet(restCommand.getUrl()); { // headers if (restCommand.useAuthorization()) { httpGet.addHeader("Authorization", restCommand.geAuthorizationHeader()); //$NON-NLS-1$ } httpGet.addHeader("Accept", "*/*;charset=utf-8"); //$NON-NLS-1$ //$NON-NLS-2$ } final HttpClient httpClient = new DefaultHttpClient(); InputStream is = null; try { final HttpResponse httpResponse = httpClient.execute(httpGet); final HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); final BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); //$NON-NLS-1$ final StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line).append('\n'); } final String content = sb.toString(); final JSONObject result = new JSONObject(content); return result; } finally { if (is != null) { try { is.close(); } catch (final IOException e) { // nothing to do } } } }
From source file:org.androidappdev.codebits.CodebitsApi.java
/** * Perform an HTTP request//from w w w .ja v a 2 s .co m * * @param url * the URL for the request * @return a String with the result of the request */ private static String performHttpRequest(String url) { StringBuilder builder = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url); try { HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line = null; while ((line = reader.readLine()) != null) { builder.append(line); } } catch (Exception e) { Log.d(TAG, "Exception", e); } return builder.toString(); }
From source file:no.hig.gsd.quizgame.ServerUtilities.java
/** * Register this account/device pair within the server. * * @return whether the registration succeeded or not. *//*from w w w .j a va 2s.c o m*/ public static String register(final Context context, final String regId) { Log.i("remote", "registering device (regId = " + regId + ")"); String usm = LoginActivity.usm; String retSrc = ""; try { HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://89.250.116.142/Quizgame/jaxrs/quizgame/gcm"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("username", usm)); nameValuePairs.add(new BasicNameValuePair("regId", regId)); post.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8)); HttpResponse httpResponse = client.execute(post); HttpEntity entity = httpResponse.getEntity(); retSrc = EntityUtils.toString(entity); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (retSrc.equals("success")) { return status = "success"; } else { return status = "failure"; } }
From source file:org.ow2.bonita.facade.rest.apachehttpclient.ApacheHttpClientUtil.java
public static HttpClient getHttpClient(String serverAddress, String username, String password) throws URISyntaxException { URI serverURI = new URI(serverAddress); DefaultHttpClient client = new DefaultHttpClient(); AuthScope authScope = new AuthScope(serverURI.getHost(), serverURI.getPort(), AuthScope.ANY_REALM, AuthScope.ANY_SCHEME);// ww w . jav a 2 s .com UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); client.getCredentialsProvider().setCredentials(authScope, credentials); return client; }
From source file:Main.java
public static void PostRequest(String url, Map<String, String> params, String userName, String password, Handler messageHandler) { HttpPost postMethod = new HttpPost(url); List<NameValuePair> nvps = null; DefaultHttpClient client = new DefaultHttpClient(); if ((userName != null) && (userName.length() > 0) && (password != null) && (password.length() > 0)) { client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password)); }/*from w w w .j a v a 2 s.c o m*/ final Map<String, String> sendHeaders = new HashMap<String, String>(); sendHeaders.put(CONTENT_TYPE, MIME_FORM_ENCODED); client.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { for (String key : sendHeaders.keySet()) { if (!request.containsHeader(key)) { request.addHeader(key, sendHeaders.get(key)); } } } }); if ((params != null) && (params.size() > 0)) { nvps = new ArrayList<NameValuePair>(); for (String key : params.keySet()) { nvps.add(new BasicNameValuePair(key, params.get(key))); } } if (nvps != null) { try { postMethod.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } ExecutePostRequest(client, postMethod, GetResponseHandlerInstance(messageHandler)); }