예제 #1
0
  public HttpUtils(int connTimeout) {
    HttpParams params = new BasicHttpParams();

    ConnManagerParams.setTimeout(params, connTimeout);
    HttpConnectionParams.setSoTimeout(params, connTimeout);
    HttpConnectionParams.setConnectionTimeout(params, connTimeout);

    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(10));
    ConnManagerParams.setMaxTotalConnections(params, 10);

    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params, 1024 * 8);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SimpleSSLSocketFactory.getSocketFactory(), 443));

    httpClient =
        new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);
    try {
      if (ComParams.userAgent != null) {
        configUserAgent(ComParams.userAgent);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_RETRY_TIMES));

    httpClient.addRequestInterceptor(
        new HttpRequestInterceptor() {
          @Override
          public void process(org.apache.http.HttpRequest httpRequest, HttpContext httpContext)
              throws HttpException, IOException {
            if (!httpRequest.containsHeader(HEADER_ACCEPT_ENCODING)) {
              httpRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
          }
        });

    httpClient.addResponseInterceptor(
        new HttpResponseInterceptor() {
          @Override
          public void process(HttpResponse response, HttpContext httpContext)
              throws HttpException, IOException {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
              return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
              for (HeaderElement element : encoding.getElements()) {
                if (element.getName().equalsIgnoreCase("gzip")) {
                  response.setEntity(new GZipDecompressingEntity(response.getEntity()));
                  return;
                }
              }
            }
          }
        });
  }
예제 #2
0
 private String sendBasic(HttpRequestBase request) throws HttpException {
   try {
     HttpResponse response = httpClient.execute(request);
     HttpEntity entity = response.getEntity();
     String body = "";
     if (entity != null) {
       body = EntityUtils.toString(entity, UTF_8);
       if (entity.getContentType() == null) {
         body = new String(body.getBytes(ISO_8859_1), UTF_8);
       }
     }
     int code = response.getStatusLine().getStatusCode();
     if (code < 200 || code >= 300) {
       throw new Exception(String.format(" code : '%s' , body : '%s'", code, body));
     }
     return body;
   } catch (Exception ex) {
     throw new HttpException(
         "Fail to send "
             + request.getMethod()
             + " request to url "
             + request.getURI()
             + ", "
             + ex.getMessage(),
         ex);
   } finally {
     request.releaseConnection();
   }
 }
예제 #3
0
  protected String getRallyAPIError(String responseXML) {
    String errorMsg = "";

    try {

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Errors");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Element item = (Element) iter.next();
        errorMsg = item.getChildText("OperationResultError");
      }

    } catch (Exception e) {
      errorMsg = e.toString();
    }

    return errorMsg;
  }
예제 #4
0
 public void run() {
   HttpPost httpPost =
       new HttpPost(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp));
   //
   httpPost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
   //
   HttpResponse response = null; // This is acting as keep alive.
   //
   while (isActive()) {
     try {
       Thread.sleep(KEEP_ALIVE_PERIOD);
       httpPost.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8));
       response = null;
       response = httpclient.execute(httpPost);
       int status = response.getStatusLine().getStatusCode();
       if (status != RestStreamHanlder.SUCCESS_200) {
         logger.error(
             "Cant register to the remote client, retrying in:"
                 + (KEEP_ALIVE_PERIOD / 1000)
                 + " seconds.");
         structure = registerAndGetStructure();
       }
     } catch (Exception e) {
       logger.warn(e.getMessage(), e);
     } finally {
       if (response != null) {
         try {
           response.getEntity().getContent().close();
         } catch (Exception e) {
           logger.warn(e.getMessage(), e);
         }
       }
     }
   }
 }
예제 #5
0
 /** @return {@link InputStream} from a {@link HttpResponse} */
 InputStream getStream(HttpResponse response) {
   try {
     return response.getEntity().getContent();
   } catch (Exception e) {
     log.error("Error reading response. " + e.getMessage());
     throw new CouchDbException(e);
   }
 }
예제 #6
0
 public String httpPost(String url) throws Exception {
   try {
     HttpPost httpPost = new HttpPost(url);
     return doPost(httpPost);
   } catch (Exception e) {
     logger.error("HttpClientUtil error : [{}].", e.getMessage(), e);
     throw e;
   }
 }
예제 #7
0
  public static final void main(String[] args) throws Exception {
    String uri = args[0];
    int reqNum = Integer.parseInt(args[1]);
    int reqTerm = Integer.parseInt(args[2]);

    try {
      // new ClientSimple().request1(uri, reqNum, reqTerm);
      new ClientSimple().request2(uri, reqNum, reqTerm);
    } catch (Exception e) {
      System.out.println("ERROR:" + e.getMessage());
    }
  }
예제 #8
0
  /** URL參數map 自定義header Create by : 2015年9月14日 上午11:02:05 */
  public String httpPost(
      String httpUrl, Map<String, String> paramMap, Map<String, String> headerMap)
      throws Exception {
    try {
      HttpPost httpPost = new HttpPost(httpUrl);
      setParam(httpPost, paramMap);
      setHeader(httpPost, headerMap);

      return doPost(httpPost);
    } catch (Exception e) {
      logger.error("HttpClientUtil error : [{}].", e.getMessage(), e);
      throw e;
    }
  }
예제 #9
0
 public static void main(String[] args) throws Exception {
   HttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager());
   TestMgrKind testMgeKind = new TestMgrKind();
   TestLogin testLogin = new TestLogin();
   try {
     testLogin.loginToSystem(httpclient, "tomcat", "tomcat", "a12345");
     HttpEntity entityKindList = testMgeKind.kindList(httpclient);
     String content = EntityUtils.toString(entityKindList);
     Document doc = Jsoup.parse(content);
     System.out.println(doc.getElementsByTag("table").get(3).text().contains("·¿²ú"));
   } catch (Exception e) {
     e.printStackTrace();
   } finally {
     httpclient.getConnectionManager().shutdown();
   }
 }
예제 #10
0
  HttpClient() {
    try {
      PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
      SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
      connManager.setDefaultSocketConfig(socketConfig);
      MessageConstraints messageConstraints =
          MessageConstraints.custom().setMaxHeaderCount(200).setMaxLineLength(2000).build();
      ConnectionConfig connectionConfig =
          ConnectionConfig.custom()
              .setMalformedInputAction(CodingErrorAction.IGNORE)
              .setUnmappableInputAction(CodingErrorAction.IGNORE)
              .setCharset(Consts.UTF_8)
              .setMessageConstraints(messageConstraints)
              .build();
      connManager.setDefaultConnectionConfig(connectionConfig);
      connManager.setMaxTotal(MAX_TOTAL_CONNECTIONS);
      connManager.setDefaultMaxPerRoute(MAX_ROUTE_CONNECTIONS);
      connManager.setMaxPerRoute(new HttpRoute(DEFAULT_TARGETHOST), 50);

      HttpRequestRetryHandler retryHandler =
          new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(
                IOException exception, int executionCount, HttpContext context) {
              if (executionCount >= 5) return false;
              if (exception instanceof InterruptedIOException) return false;
              if (exception instanceof UnknownHostException) return false;
              if (exception instanceof ConnectTimeoutException) return false;
              if (exception instanceof SSLException) return false;
              HttpClientContext clientContext = HttpClientContext.adapt(context);
              HttpRequest request = clientContext.getRequest();
              boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
              if (idempotent) return true;
              return false;
            }
          };

      httpClient =
          HttpClients.custom()
              .setConnectionManager(connManager)
              .setRetryHandler(retryHandler)
              .build();
    } catch (Exception e) {
      logger.error("HttpClientUtil error : [{}].", e.getMessage(), e);
    }
  }
  public @Nullable <T> T get(Class<T> classType, @Nonnull URI uri)
      throws CloudException, InternalException {
    InputStream responseAsStream = getAsStream(provider.getContext().getAccountNumber(), uri);

    if (responseAsStream == null) {
      logger.info("Unable to perform HTTP GET at following resource: " + uri.toString());
      return null;
    }
    try {
      JAXBContext context = JAXBContext.newInstance(classType);
      Unmarshaller u = context.createUnmarshaller();
      return (T) u.unmarshal(responseAsStream);
    } catch (Exception ex) {
      logger.error(ex.getMessage());
      throw new InternalException(ex);
    }
  }
예제 #12
0
  /** JSON格式傳遞參數 自定義header Create by : 2015年9月2日 下午2:52:24 */
  public String httpPost(String url, String msg, Map<String, String> headerMap) throws Exception {
    try {
      StringEntity stringEntity = new StringEntity(msg, "utf-8"); // 解决中文乱码问题
      stringEntity.setContentType("application/json");

      logger.debug("json param:{}", msg);

      HttpPost httpPost = new HttpPost(url);
      httpPost.setEntity(stringEntity);

      setHeader(httpPost, headerMap);

      return doPost(httpPost);
    } catch (Exception e) {
      logger.error("HttpClientUtil error : [{}].", e.getMessage(), e);
      throw e;
    }
  }
예제 #13
0
  public boolean initialize() {

    try {
      initParams = new RemoteWrapperParamParser(getActiveAddressBean(), true);
      uid = Math.random();

      postParameters = new ArrayList<NameValuePair>();
      postParameters.add(
          new BasicNameValuePair(PushDelivery.NOTIFICATION_ID_KEY, Double.toString(uid)));
      postParameters.add(
          new BasicNameValuePair(
              PushDelivery.LOCAL_CONTACT_POINT, initParams.getLocalContactPoint()));
      // Init the http client
      if (initParams.isSSLRequired()) {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(
            new FileInputStream(new File("conf/servertestkeystore")),
            Main.getContainerConfig().getSSLKeyStorePassword().toCharArray());
        SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
        socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        int sslPort =
            Main.getContainerConfig().getSSLPort() > 0
                ? Main.getContainerConfig().getSSLPort()
                : ContainerConfig.DEFAULT_SSL_PORT;
        Scheme sch = new Scheme("https", socketFactory, sslPort);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);
      }
      Scheme plainsch =
          new Scheme(
              "http",
              PlainSocketFactory.getSocketFactory(),
              Main.getContainerConfig().getContainerPort());
      httpclient.getConnectionManager().getSchemeRegistry().register(plainsch);
      //
      lastReceivedTimestamp = initParams.getStartTime();
      structure = registerAndGetStructure();
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
      NotificationRegistry.getInstance().removeNotification(uid);
      return false;
    }

    return true;
  }
예제 #14
0
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.receiver);

    final Button cancelbtn = (Button) findViewById(R.id.ButtonCancel);
    // cancelbtn.setEnabled(false);
    cancelbtn.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            // streamtask.cancel(true);
            finish();
          }
        });

    try {
      Intent intent = getIntent();
      String action = intent.getAction();
      String type = intent.getType();

      if ((!(Intent.ACTION_SEND.equals(action))) || (type == null)) {
        throw new RuntimeException("Unknown intent action or type");
      }

      if (!("text/plain".equals(type))) {
        throw new RuntimeException("Type is not text/plain");
      }

      String extra = intent.getStringExtra(Intent.EXTRA_TEXT);
      if (extra == null) {
        throw new RuntimeException("Cannot get shared text");
      }

      final DownloadStreamTask streamtask = new DownloadStreamTask(this);

      //	Once created, a task is executed very simply:
      streamtask.execute(extra);

    } catch (Exception e) {
      Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
    }
  }
예제 #15
0
  public void request1(String uri, int reqNum, int reqTerm) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    if (reqNum == 0) {
      System.out.println(
          String.format("request to %s infinite times with term '%d' ms", uri, reqTerm));
    } else {
      System.out.println(
          String.format("request to %s '%d' times with term '%d' ms", uri, reqNum, reqTerm));
    }

    int i = 0, tick = 0;
    HttpGet httpGet = new HttpGet(uri);
    CloseableHttpResponse response;
    HttpEntity entity;

    while (true) {
      usleep(reqTerm);
      tick = (int) (Math.random() * 10) % 2;
      if (tick == 0) {
        continue;
      }
      System.out.println("request " + httpGet.getURI());
      response = httpclient.execute(httpGet);
      System.out.println("--> response status  = " + response.getStatusLine());
      // response handler
      try {
        entity = response.getEntity();
        EntityUtils.consume(entity);
      } catch (Exception e) {
        System.out.println("  --> http fail:" + e.getMessage());
      } finally {
        // Thread.sleep(5000); //테스트에만 썼다. close 지연시키려고.
        response.close();
      }

      System.out.println("----------------------------------------");
      if (reqNum != 0 && reqNum < ++i) {
        break;
      }
    }
  }
예제 #16
0
  /** header由調用者set Create by : 2015年9月14日 上午11:54:59 */
  private String doPost(HttpPost httpPost) throws Exception {
    try {
      httpPost.setConfig(config);
      /**
       * setHeader(name, value):如果Header中没有定义则添加,如果已定义则用新的value覆盖原用value值。 addHeader(name,
       * value):如果Header中没有定义则添加,如果已定义则保持原有value不改变。
       */
      //			httpPost.addHeader( HTTP.CONTENT_TYPE, "application/json" ) ;
      //			httpPost.addHeader( "Accept-Charset", "gbk,GB2312,utf-8;q=0.7,*;q=0.7" ) ;
      //			httpPost.addHeader( "Accept-Language", "zh-cn,zh;q=0.5" ) ;
      //			httpPost.addHeader( HTTP.CONN_DIRECTIVE, "keep-alive" ) ;
      //			httpPost.addHeader( "refer", "localhost" ) ;
      //			httpPost.addHeader( HTTP.USER_AGENT, "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2)
      // Gecko/20100101 Firefox/6.0.2" ) ;

      CloseableHttpResponse response = httpClient.execute(httpPost, HttpClientContext.create());
      try {
        HttpEntity entity = response.getEntity();
        logger.debug("{}", entity);

        return EntityUtils.toString(entity);
        //				return EntityUtils.toString( entity, "utf-8" );
      } finally {
        if (null != response) response.close();
      }
    } catch (ClientProtocolException e) {
      logger.error("HttpClientUtil error : [{}].", e.getMessage(), e);
      throw e;
    } catch (ParseException e) {
      logger.error("HttpClientUtil error : [{}].", e.getMessage(), e);
      throw e;
    } catch (IOException e) {
      logger.error("HttpClientUtil error : [{}].", e.getMessage(), e);
      throw e;
    } catch (Exception e) {
      logger.error("HttpClientUtil error : [{}].", e.getMessage(), e);
      throw e;
    }
  }
예제 #17
0
  private boolean saveAndVerify(ZipInputStream data) throws IOException {
    try {
      ZipEntry ze;
      while ((ze = data.getNextEntry()) != null) {
        // Filename + reference to file.
        String filename = ze.getName();
        File output = new File(local_path + filename);

        if (filename.endsWith("/")) {
          output.mkdirs();
        } else {
          if (output.exists()) {
            // Delete the file if it already exists.
            if (!output.delete()) {
              return false;
            }
          }
          if (output.createNewFile()) {
            FileOutputStream out = new FileOutputStream(output);
            byte[] buffer = new byte[1024];
            int count;
            while ((count = data.read(buffer)) != -1) {
              out.write(buffer, 0, count);
            }
          } else {
            return false;
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    } finally {
      data.close();
    }
    return true;
  }
예제 #18
0
  /** @return {@link DefaultHttpClient} instance. */
  private HttpClient createHttpClient(CouchDbProperties props) {
    DefaultHttpClient httpclient = null;
    try {
      SchemeSocketFactory ssf = null;
      if (props.getProtocol().equals("https")) {
        TrustManager trustManager =
            new X509TrustManager() {
              public void checkClientTrusted(X509Certificate[] chain, String authType)
                  throws CertificateException {}

              public void checkServerTrusted(X509Certificate[] chain, String authType)
                  throws CertificateException {}

              public X509Certificate[] getAcceptedIssuers() {
                return null;
              }
            };
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(null, new TrustManager[] {trustManager}, null);
        ssf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SSLSocket socket = (SSLSocket) ssf.createSocket(null);
        socket.setEnabledCipherSuites(new String[] {"SSL_RSA_WITH_RC4_128_MD5"});
      } else {
        ssf = PlainSocketFactory.getSocketFactory();
      }
      SchemeRegistry schemeRegistry = new SchemeRegistry();
      schemeRegistry.register(new Scheme(props.getProtocol(), props.getPort(), ssf));
      PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry);
      httpclient = new DefaultHttpClient(ccm);
      host = new HttpHost(props.getHost(), props.getPort(), props.getProtocol());
      context = new BasicHttpContext();
      // Http params
      httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
      httpclient
          .getParams()
          .setParameter(CoreConnectionPNames.SO_TIMEOUT, props.getSocketTimeout());
      httpclient
          .getParams()
          .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, props.getConnectionTimeout());
      int maxConnections = props.getMaxConnections();
      if (maxConnections != 0) {
        ccm.setMaxTotal(maxConnections);
        ccm.setDefaultMaxPerRoute(maxConnections);
      }
      if (props.getProxyHost() != null) {
        HttpHost proxy = new HttpHost(props.getProxyHost(), props.getProxyPort());
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
      }
      // basic authentication
      if (props.getUsername() != null && props.getPassword() != null) {
        httpclient
            .getCredentialsProvider()
            .setCredentials(
                new AuthScope(props.getHost(), props.getPort()),
                new UsernamePasswordCredentials(props.getUsername(), props.getPassword()));
        props.clearPassword();
        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(host, basicAuth);
        context.setAttribute(ClientContext.AUTH_CACHE, authCache);
      }
      // request interceptor
      httpclient.addRequestInterceptor(
          new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context)
                throws IOException {
              if (log.isInfoEnabled()) {
                RequestLine requestLine = request.getRequestLine();
                try {
                  log.info(
                      ">> "
                          + (new StringBuilder())
                              .append(">> ")
                              .append(requestLine.getMethod())
                              .append(" ")
                              .append(urlCodec.decode(requestLine.getUri()))
                              .toString());
                } catch (DecoderException e) {
                  log.error(e, e);
                }
              }
            }
          });
      // response interceptor
      httpclient.addResponseInterceptor(
          new HttpResponseInterceptor() {
            public void process(final HttpResponse response, final HttpContext context)
                throws IOException {
              validate(response);
              if (log.isInfoEnabled())
                log.info("<< Status: " + response.getStatusLine().getStatusCode());
            }
          });
    } catch (Exception e) {
      log.error("Error Creating HTTP client. " + e.getMessage());
      throw new IllegalStateException(e);
    }
    return httpclient;
  }
예제 #19
0
    @Override
    protected String doInBackground(Void... voidstr) {
      JSONObject jsonObject = new JSONObject();

      try {
        jsonObject.accumulate("firstName", firstName);
        jsonObject.accumulate("lastName", lastName);
        jsonObject.accumulate("phoneNumber", phoneNumber);
        jsonObject.accumulate("address", addr);

        // Add a nested JSONObject (e.g. for header information)
        JSONObject header = new JSONObject();
        header.put("deviceType", "Android"); // Device type
        header.put("deviceVersion", "2.0"); // Device OS version
        header.put("language", "es-es"); // Language of the Android client
        jsonObject.put("header", header);
        // Output the JSON object we're sending to Logcat:

        URL = "http://162.243.114.166/cgi-bin/Database_scripts/Registration_script.py";
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);
        System.out.println("printing json object : " + jsonObject);
        String se;
        se = jsonObject.toString();
        System.out.println("printing se : " + se);

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        System.out.println("printing req : " + httpPostRequest.getEntity().getContent().toString());
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        // httpPostRequest.setHeader("Content-length", IntegejsonObjSend.toString().length());
        // httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you
        // would like to use gzip compression

        InputStream inp = httpPostRequest.getEntity().getContent();
        String req = convertStreamToString(inp);
        System.out.println("printing entities : " + req);

        System.out.println("printing http request message : message is :" + httpPostRequest);
        HttpResponse response = null;
        try {
          response = (HttpResponse) httpclient.execute(httpPostRequest);
        } catch (Exception ex) {
          System.out.println("printing error :" + ex);
        }
        InputStream is = response.getEntity().getContent();
        String res = convertStreamToString(is);
        System.out.println("printing Response is :" + res);
        System.out.println("printing response code : " + response.getStatusLine().getStatusCode());

        // Get hold of the response entity (-> the data)
        HttpEntity entity = response.getEntity();
        String serverresp = entity.toString();
        System.out.println(
            "printing server response, entity length : " + entity.getContentLength());
        System.out.println("printing server response : " + serverresp);

        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);
          }
          System.out.println("Debug point : 1.3");
          // convert content stream to a String
          String resultString = convertStreamToString(instream);
          instream.close();
          resultString =
              resultString.substring(1, resultString.length() - 1); // remove wrapping "[" and "]"

          // Transform the String into a JSONObject
          JSONObject jsonObjRecv = new JSONObject(resultString);
          // Raw DEBUG output of our received JSON object:
          Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>");
          System.out.println("Debug point : 1.4");
          return jsonObjRecv;
        }
        // return serverresp;

        try {
          // Add your data
          List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
          nameValuePairs.add(new BasicNameValuePair("q", se));
          httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs));
          System.out.println("printing http params: " + httpPostRequest.getParams().toString());
          // Execute HTTP Post Request
          HttpResponse response = httpclient.execute(httpPostRequest);

        } catch (ClientProtocolException e) {
          // TODO Auto-generated catch block
        } catch (IOException e) {
          // TODO Auto-generated catch block
        }
      } catch (Exception e) {
        System.out.println("Debug point : 1.4(a)");
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
      }
      return null;
    }
예제 #20
-52
    @Override
    protected String[] doInBackground(String... parms) {
      String[] resultarr = new String[1];
      String intentstr = parms[0];

      // int count = urls.length;
      // long totalSize = 0; for (int i = 0; i < count; i++) { totalSize +=
      // Downloader.downloadFile(urls[i]);
      // publishProgress((int) ((i / (float) count) * 100));
      // Escape early if cancel() is called
      // if (isCancelled())
      //		break;

      try {
        // Connect to API and authenticate
        publishProgress("Connecting and authenticating API session...");

        ApiWrapper wrapper;
        // wrapper = Api.wrapper;
        wrapper = new ApiWrapper(Api.mClientID, Api.mClientSecret, null, null);
        wrapper.login("un1tz3r0", "Farscap3");

        publishProgress("Resolving url...");

        String resolvedurl = resolveURL(wrapper, intentstr);

        publishProgress("Getting metadata...");

        HttpResponse resp = wrapper.get(Request.to(resolvedurl));

        JSONObject jso = Http.getJSON(resp);
        // resultstr = jso.toString();

        if (jso.getString("kind").equals("track")) {
          if (jso.getBoolean("downloadable")) {
            publishProgress("Getting download redirect URL...");

            String dlrurl =
                wrapper
                    .getURI(
                        Request.to(jso.getString("download_url")).add("allow_redirect", false),
                        false,
                        false)
                    .toString();
            HttpResponse dlrresp = wrapper.get(Request.to(dlrurl));
            String dlstr = dlrurl;
            if (dlrresp.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
              Header dlloch = dlrresp.getFirstHeader("location");
              if ((dlloch == null) || (dlloch.getValue() == null))
                throw new RuntimeException("Download url HEAD response has no location header");

              dlstr = wrapper.getURI(Request.to(dlloch.getValue()), false, false).toString();
            } else if (dlrresp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
              dlstr = dlrurl;
            } else {
              throw new RuntimeException(
                  "Download url HEAD response has wrong status ("
                      + String.valueOf(dlrresp.getStatusLine().getStatusCode())
                      + " "
                      + dlrresp.getStatusLine().getReasonPhrase()
                      + ")");
            }
            // String dlstr = Request.to( dlloch.getValue() ).add("CLIENT_ID",
            // Api.mClientID).toString();

            //												if(dlresp2.getStatusLine().getStatusCode() !=
            // HttpStatus.SC_MOVED_TEMPORARILY)
            //														throw new RuntimeException("Download redirect url HEAD response has
            // wrong status: " + dlresp2.getStatusLine().toString());
            //												Header dlloc2 = dlresp2.getFirstHeader("location");
            //												if((dlloc2 == null) || (dlloc2.getValue() == null))
            //														throw new RuntimeException("Download redirect url HEAD response has no
            // location header");
            //

            resultarr = new String[2];
            resultarr[1] =
                jso.getString("title").replaceAll("[^A-Za-z0-9 -]*", "")
                    + "."
                    + jso.getString("original_format");
            resultarr[0] = dlstr;
          } else {
            Stream st = wrapper.resolveStreamUrl(jso.getString("stream_url"), true);
            resultarr = new String[2];
            resultarr[1] = jso.getString("title").replaceAll("[^A-Za-z0-9 -]*", "").concat(".mp3");
            resultarr[0] = st.streamUrl;
          }
        }
      } catch (JSONException e) {
        resultarr = new String[1];
        resultarr[0] = e.toString();
      } catch (IOException e) {
        resultarr = new String[1];
        resultarr[0] = e.toString();
      } catch (Exception e) {
        resultarr = new String[1];
        resultarr[0] = e.toString();
      }

      return resultarr;
    }