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

Following code examples demonstrate how to use org.apache.http.util.EntityUtilsfrom android. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use org.apache.http.util.EntityUtilsand various code implementation of this class.

    if (statusCode > 299) {
      throw new RuntimeException("could not upload " + pathToRpm + " to " + repoUrl + "\nResponseCode:" + statusCode +
        "\nResponsebody: " + EntityUtils.toString(response.getEntity()));
    } 


    
    public String makeServiceCall(String url, int method,
                                  List<NameValuePair> params) {
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }

                httpResponse = httpClient.execute(httpPost);

            } else if (method == GET) {
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return response;

    } 

	public static void post( String form, String content_type ){
		if( mClient == null )
			mClient = new DefaultHttpClient();
		try{
			List<NameValuePair> pairs = new ArrayList<NameValuePair>();
			pairs.add(new BasicNameValuePair( "form", form) );
			pairs.add( new BasicNameValuePair( "content-type", content_type) );
			post.setEntity( new UrlEncodedFormEntity( pairs ) );
			BasicHttpResponse response = (BasicHttpResponse) mClient.execute( post );
			BasicManagedEntity ent = (BasicManagedEntity)response.getEntity();
			String responseText = EntityUtils.toString( ent );
		}catch( ClientProtocolException e){
			e.printStackTrace();
		}catch( IOException e ){
			e.printStackTrace();
		}
	} 

  
  public <T> T execute(HttpHost paramHttpHost, HttpRequest paramHttpRequest, ResponseHandler<? extends T> paramResponseHandler, HttpContext paramHttpContext)
  {
    paramHttpHost = execute(paramHttpHost, paramHttpRequest, paramHttpContext);
    try
    {
      paramHttpRequest = paramResponseHandler.handleResponse(paramHttpHost);
      return paramHttpRequest;
    }
    finally
    {
      paramHttpHost = paramHttpHost.getEntity();
      if (paramHttpHost != null) {
        EntityUtils.consume(paramHttpHost);
      }
    }
  } 

    public Page visit(String url) {
        logger.info(" 访问:{}",url);
        Page page = null;
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(50000)
                .setConnectionRequestTimeout(10000)
                .setSocketTimeout(50000)
                .build();

        CloseableHttpClient httpClient =HttpClients.custom()
                .setRetryHandler(new DefaultHttpRequestRetryHandler())
                .setDefaultRequestConfig(config)
                .setUserAgent("Mozilla/5.0(Windows;U;Windows NT 5.1;en-US;rv:0.9.4)")
                .build();

        HttpUriRequest request = RequestBuilder.get(url).build();

        try {
            CloseableHttpResponse response = httpClient.execute(request);
            if(response.getStatusLine().getStatusCode()!= HttpStatus.SC_OK){
                logger.info("访问{}失败,状态码为{}",url,response.getStatusLine().getStatusCode());
            }else {
                HttpEntity entity = response.getEntity();
                byte[] responseBody = EntityUtils.toByteArray(entity);
                String contentType = entity.getContentType().getName();

                page = new Page(responseBody, url, contentType);
            }
        } catch (IOException e) {
            logger.warn("访问"+url+"时出现IO异常",e);
            throw new RuntimeException("访问"+url+"时出现IO异常");
        }finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.warn("关闭"+url+"对应的HTTPClient时出现IO异常",e);

            }
        }

        return page;
    } 

        protected String doInBackground(String... arg0) {
            String str = null;
            try {
                Uri.Builder uriBuilder = new Uri.Builder();
                uriBuilder.path(ENDPOINT_URL);
                String postUrl = Uri.decode(uriBuilder.build().toString());
                Log.d("art", postUrl);

                HttpPost httpPost = new HttpPost(postUrl);
                httpPost.setHeader("Content-type", "application/json");
                httpPost.setEntity(new StringEntity("{\"longUrl\":\"" + url + "\"}"));

                DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
                HttpParams httpParams = defaultHttpClient.getParams();
                HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_IN_MILLIS);
                HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_IN_MILLIS);

                HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
                int statusCode = httpResponse.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    String entity = EntityUtils.toString(httpResponse.getEntity());
                    JSONObject jsonEntity = new JSONObject(entity);
                    str = jsonEntity.optString("id");
                }
            } catch (Exception ignored) {
            }
            this.listener.onShortenComplete(str);
            return str;
        } 

	public void getAccount(String AccountID) throws Exception {
		HttpClientFactory factory = new HttpClientFactory();
		HttpClient client = factory.getHttpsClient();		

		request.addHeader(BankRestApiModel.getHeaderAuthKey(), BankRestApiModel.getHeaderAuthValue());
		HttpResponse response = client.execute(request);
		HttpEntity entity = response.getEntity();

		BufferedReader rd = new BufferedReader
			    (new InputStreamReader(
			    entity.getContent()));
				String jsonString = EntityUtils.toString(entity, StandardCharsets.UTF_8);
				System.out.println("HTTPS RESPONSE: " + jsonString);							
	} 

    public static String doGet(String testUrl,CookieStore store) throws IOException {
        String result;
        HttpGet get = new HttpGet(testUrl);
        DefaultHttpClient client = new DefaultHttpClient();

        client.setCookieStore(store);

        HttpResponse response = client.execute(get);

        int statusCode = response.getStatusLine().getStatusCode();
        System.out.println("statusCode = " + statusCode);

        if(statusCode == 200){
            result = EntityUtils.toString(response.getEntity(),"utf-8");
            System.out.println("aaaa" + result);
            return result;
        }else{
            return "error";
        }
    } 

    public static String doPost(String testUrl,CookieStore store) throws IOException {
        String res=null;
        DefaultHttpClient client = new DefaultHttpClient();


        HttpPost post = new HttpPost(testUrl);
        JSONObject param = new JSONObject();
        param.put("name","huhansan");
        param.put("age","18");

        post.setHeader("content-type","application/json");

        StringEntity entity = new StringEntity(param.toString(),"utf-8");
        post.setEntity(entity);
        String result;
        client.setCookieStore(store);
        HttpResponse response = client.execute(post);
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println(result);
        JSONObject resultJson = new JSONObject(result);
        String success = (String)resultJson.get("huhansan");
        String status = (String)resultJson.get("status");

        return success + status;
    } 

Advertisement
Advertisement