Java Code Examples for org.apache.http.client.HttpClient#execute()

The following examples show how to use org.apache.http.client.HttpClient#execute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClientUtils.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
/**
 * Method posts request payload
 * 
 * @param request
 * @param payload
 * @return
 */
protected HttpResponse sendPayload(HttpEntityEnclosingRequestBase request, byte[] payload, HttpHost proxy) {
  HttpResponse response = null;
  boolean ok = false;
  int tryCount = 0;
  while (!ok) {
    try {
      tryCount++;
      HttpClient httpclient = new DefaultHttpClient();
      if(proxy != null) {
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
      }
      request.setEntity(new ByteArrayEntity(payload));
      log(request);
      response = httpclient.execute(request);
      ok = true;
    } catch(IOException ioe) {
      if (tryCount <= retryCount) {
        ok = false;
      } else {
        throw new EFhirClientException("Error sending HTTP Post/Put Payload: "+ioe.getMessage(), ioe);
      }
    }
  }
  return response;
}
 
Example 2
Source File: AliHttpUtils.java    From charging_pile_cloud with MIT License 6 votes vote down vote up
/**
 * Put String
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param body
 * @return
 * @throws Exception
 */
public static HttpResponse doPut(String host, String path, String method,
                                 Map<String, String> headers,
                                 Map<String, String> querys,
                                 String body)
        throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPut request = new HttpPut(buildUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
    }

    if (StringUtils.isNotBlank(body)) {
        request.setEntity(new StringEntity(body, "utf-8"));
    }

    return httpClient.execute(request);
}
 
Example 3
Source File: CaiPiaoHttpUtils.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
/**
 * Post String
 * 
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param body
 * @return
 * @throws Exception
 */
public static HttpResponse doPost(String host, String path, String method, 
		Map<String, String> headers, 
		Map<String, String> querys, 
		String body)
           throws Exception {    	
   	HttpClient httpClient = wrapClient(host);

   	HttpPost request = new HttpPost(buildUrl(host, path, querys));
       for (Map.Entry<String, String> e : headers.entrySet()) {
       	request.addHeader(e.getKey(), e.getValue());
       }

       if (StringUtils.isNotBlank(body)) {
       	request.setEntity(new StringEntity(body, "utf-8"));
       }

       return httpClient.execute(request);
   }
 
Example 4
Source File: MainActivity.java    From android-advanced-light with MIT License 6 votes vote down vote up
private void useHttpClientPost(String url) {
    HttpPost mHttpPost = new HttpPost(url);
    mHttpPost.addHeader("Connection", "Keep-Alive");
    try {
        HttpClient mHttpClient = createHttpClient();
        List<NameValuePair> postParams = new ArrayList<>();
        //要传递的参数
        postParams.add(new BasicNameValuePair("ip", "59.108.54.37"));
        mHttpPost.setEntity(new UrlEncodedFormEntity(postParams));
        HttpResponse mHttpResponse = mHttpClient.execute(mHttpPost);
        HttpEntity mHttpEntity = mHttpResponse.getEntity();
        int code = mHttpResponse.getStatusLine().getStatusCode();
        if (null != mHttpEntity) {
            InputStream mInputStream = mHttpEntity.getContent();
            String respose = converStreamToString(mInputStream);
            Log.d(TAG, "请求状态码:" + code + "\n请求结果:\n" + respose);
            mInputStream.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 5
Source File: HttpClientUtils.java    From uReplicator with Apache License 2.0 6 votes vote down vote up
public static String getData(final HttpClient httpClient,
    final RequestConfig requestConfig,
    final String host,
    final int port,
    final String path) throws IOException, URISyntaxException {
  URI uri = new URIBuilder()
      .setScheme("http")
      .setHost(host)
      .setPort(port)
      .setPath(path)
      .build();

  HttpGet httpGet = new HttpGet(uri);
  httpGet.setConfig(requestConfig);

  return httpClient.execute(httpGet, HttpClientUtils.createResponseBodyExtractor(path));
}
 
Example 6
Source File: SegmentPushControllerAPIs.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private boolean deleteSegment(String tablename, String segmentName) throws IOException {
  boolean deleteSuccessful = false;

  HttpClient controllerClient = new DefaultHttpClient();
  HttpDelete req = new HttpDelete(SEGMENTS_ENDPOINT + URLEncoder.encode(tablename, UTF_8) + "/"
      + URLEncoder.encode(segmentName, UTF_8)
      + TYPE_PARAMETER);
  HttpResponse res = controllerClient.execute(controllerHttpHost, req);
  try {
    if (res == null || res.getStatusLine() == null || res.getStatusLine().getStatusCode() != 200
        || !isDeleteSuccessful(tablename, segmentName)) {
      LOGGER.info("Exception in deleting segment, trying again {}", res);
    } else {
      deleteSuccessful = true;
    }
  } finally {
    if (res.getEntity() != null) {
      EntityUtils.consume(res.getEntity());
    }
  }
  return deleteSuccessful;
}
 
Example 7
Source File: ClientUtils.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param request
 * @param payload
 * @return
 */
protected HttpResponse sendRequest(HttpUriRequest request) {
  HttpResponse response = null;
  try {
    HttpClient httpclient = new DefaultHttpClient();
    log(request);
    HttpParams params = httpclient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, timeout);
    HttpConnectionParams.setSoTimeout(params, timeout);
    if(proxy != null) {
      httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    response = httpclient.execute(request);
  } catch(IOException ioe) {
    throw new EFhirClientException("Error sending Http Request: "+ioe.getMessage(), ioe);
  }
  return response;
}
 
Example 8
Source File: MultiController.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
private boolean emailPassword(String password, String username, String email) {
    HttpClient client = new DefaultHttpClient();
    try {
        HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
        HttpConnectionParams.setSoTimeout(client.getParams(), 10000);
        HttpPost method = new HttpPost("http://subsonic.org/backend/sendMail.view");

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("from", "[email protected]"));
        params.add(new BasicNameValuePair("to", email));
        params.add(new BasicNameValuePair("subject", "Subsonic Password"));
        params.add(new BasicNameValuePair("text",
                "Hi there!\n\n" +
                        "You have requested to reset your Subsonic password.  Please find your new login details below.\n\n" +
                        "Username: " + username + "\n" +
                        "Password: " + password + "\n\n" +
                        "--\n" +
                        "The Subsonic Team\n" +
                        "subsonic.org"));
        method.setEntity(new UrlEncodedFormEntity(params, StringUtil.ENCODING_UTF8));
        client.execute(method);
        return true;
    } catch (Exception x) {
        LOG.warn("Failed to send email.", x);
        return false;
    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example 9
Source File: SimpleMmiDemo.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void send(final Mmi mmi, final URI target) throws JAXBException,
        IOException {
    final JAXBContext ctx = JAXBContext.newInstance(Mmi.class);
    final Marshaller marshaller = ctx.createMarshaller();
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    marshaller.marshal(mmi, out);
    final HttpClient client = new DefaultHttpClient();
    final HttpPost post = new HttpPost(target);
    final HttpEntity entity = new StringEntity(out.toString(),
            ContentType.APPLICATION_XML);
    post.setEntity(entity);
    client.execute(post);
    LOGGER.info("sending " + mmi + " to '" + target + "'");
}
 
Example 10
Source File: HttpClientProxy.java    From bitcoin-transaction-explorer with MIT License 5 votes vote down vote up
private static HttpEntity executeRemoteContent(final HttpClient client, final boolean unsafe, final HttpUriRequest request, final HttpClientContext localContext) throws ClientProtocolException, IOException, ParseException, HttpException {
  final HttpResponse httpResponse = client.execute(request);

  if (unsafe || httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    return httpResponse.getEntity();
  } else {
    throw new HttpException(httpResponse.getStatusLine().toString() + EntityUtils.toString(httpResponse.getEntity()));
  }
}
 
Example 11
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteChunk(Workspace workspace, String chunkName) throws Exception {

    if (!isTokenActive()) {
        login();
    }

    HttpClient httpClient = new DefaultHttpClient();

    String url = this.storageUrl + "/" + workspace.getSwiftContainer() + "/" + chunkName;

    try {

        HttpDelete request = new HttpDelete(url);
        request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);

        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("401 User unauthorized");
        }

        if (swiftResponse.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            throw new ObjectNotFoundException("404 Not Found");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example 12
Source File: HttpUtil.java    From AthenaServing with Apache License 2.0 5 votes vote down vote up
public static String myHttpGet(String url){
    HttpClient httpClient = new DefaultHttpClient();
    //设置超时时间
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 3000);
    HttpGet get = new HttpGet(url);
    try{
        // 发送GET请求
        HttpResponse httpResponse = httpClient.execute(get);
        // 如果服务器成功地返回响应
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
        {
            // 获取服务器响应字符串
            String result = EntityUtils.toString(httpResponse.getEntity());
            return result;
        } else {
            // 如果服务器失败返回响应数据"error"
            return "error";
        }
    }catch(Exception e){
        // 捕获超时异常 并反馈给调用者
        e.printStackTrace();
        return "connection time out";
    }finally{
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example 13
Source File: OneFichierUploaderPlugin.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
public static void fileUpload() throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        file = new File("C:\\Documents and Settings\\dinesh\\Desktop\\FourSharedUploaderPlugin.java");
//        file = new File("e:\\dinesh.txt");
        HttpPost httppost = new HttpPost("http://upload.1fichier.com/en/upload.cgi?id=" + uid);
        if (login) {
            httppost.setHeader("Cookie", sidcookie);
        }
        MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(file);
//        mpEntity.addPart("UPLOAD_IDENTIFIER", new StringBody(uploadid));
        mpEntity.addPart("file[]", cbFile);
        mpEntity.addPart("domain", new StringBody("0"));
        httppost.setEntity(mpEntity);
        System.out.println("Now uploading your file into 1fichier...........................");
        System.out.println("Now executing......." + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
//        HttpEntity resEntity = response.getEntity();
        System.out.println(response.getStatusLine());
        if (response.containsHeader("Location")) {
            uploadresponse = response.getFirstHeader("Location").getValue();
            System.out.println("Upload location link : " + uploadresponse);
        } else {
            throw new Exception("There might be a problem with your internet connection or server error. Please try again");
        }
    }
 
Example 14
Source File: TestPrometheusRecordSink.java    From nifi with Apache License 2.0 5 votes vote down vote up
private String getMetrics() throws IOException {
    URL url = new URL("http://localhost:" + portString + "/metrics");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    int status = con.getResponseCode();
    Assert.assertEquals(HttpURLConnection.HTTP_OK, status);

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet("http://localhost:" + portString + "/metrics");
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    return EntityUtils.toString(entity);
}
 
Example 15
Source File: GRupload.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
public void fileUpload() throws Exception {

        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpPost httppost = new HttpPost(gruploadlink);
        if (gruploadAccount.loginsuccessful) {

            httppost.setHeader("Cookie", GRuploadAccount.getLogincookie() + ";" + GRuploadAccount.getXfsscookie());
        }
        MultipartEntity mpEntity = new MultipartEntity();
        mpEntity.addPart("upload_type", new StringBody("file"));
//        mpEntity.addPart("srv_id", new StringBody(serverID));
        if (gruploadAccount.loginsuccessful) {
            mpEntity.addPart("sess_id", new StringBody(GRuploadAccount.getXfsscookie().substring(5)));
        }
        mpEntity.addPart("srv_tmp_url", new StringBody(tmpserver + "/tmp"));
        mpEntity.addPart("file_0", createMonitoredFileBody());
        httppost.setEntity(mpEntity);
        NULogger.getLogger().info("Now uploading your file into grupload...........................");
        uploading();
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        NULogger.getLogger().info(response.getStatusLine().toString());
        if (resEntity != null) {

            String tmp = EntityUtils.toString(resEntity);
            NULogger.getLogger().log(Level.INFO, "Upload response : {0}", tmp);

            fnvalue = StringUtils.stringBetweenTwoStrings(tmp, "name='fn'>", "<");
            NULogger.getLogger().log(Level.INFO, "fn value : {0}", fnvalue);

        } else {
            throw new Exception("There might be a problem with your internet connection or server error. Please try again some after time. :(");
        }
    }
 
Example 16
Source File: AopHttpClient.java    From ArgusAPM with Apache License 2.0 4 votes vote down vote up
public static <T> T execute(HttpClient client, HttpHost host, HttpRequest request, ResponseHandler<? extends T> handler) throws IOException {
    NetInfo data = new NetInfo();
    return client.execute(host, handleRequest(host, request, data), AopResponseHandler.wrap(handler, data));
}
 
Example 17
Source File: QHC.java    From ArgusAPM with Apache License 2.0 4 votes vote down vote up
public static <T> T execute(HttpClient client, HttpHost host, HttpRequest request, ResponseHandler<? extends T> handler) throws IOException {
    return isTaskRunning()
            ? AopHttpClient.execute(client, host, request, handler)
            : client.execute(host, request, handler);
}
 
Example 18
Source File: AopHttpClient.java    From ArgusAPM with Apache License 2.0 4 votes vote down vote up
public static <T> T execute(HttpClient client, HttpHost host, HttpRequest request, ResponseHandler<? extends T> handler, HttpContext context) throws IOException {
    NetInfo data = new NetInfo();
    return client.execute(host, handleRequest(host, request, data), AopResponseHandler.wrap(handler, data), context);
}
 
Example 19
Source File: Neo4jIT.java    From baleen with Apache License 2.0 4 votes vote down vote up
@Test
public void testDocumentGraphConsumer()
    throws AnalysisEngineProcessException, ResourceInitializationException, IOException,
        URISyntaxException {

  String rootUrl = "http://localhost:" + neo4j.getMappedPort(NEO_PORT);
  setPassword(rootUrl);

  JCasTestGraphUtil.populateJcas(jCas);

  processJCas(
      Neo4JDocumentGraphConsumer.PARAM_NEO4J_URL,
      "bolt://localhost:" + neo4j.getMappedPort(7687),
      Neo4JDocumentGraphConsumer.PARAM_NEO4J_PASSWORD,
      PASS);

  String url = rootUrl + "/db/data/cypher";

  HttpClient client = createClient(PASS);

  HttpPost post = new HttpPost(url);

  post.setHeader("Accept", "application/json");
  post.setHeader("Content-Type", "application/json");

  String json = "{ \"query\" : \"MATCH (x) WHERE x.value = 'John Smith' RETURN x\" }";

  StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
  post.setEntity(entity);

  HttpResponse response = client.execute(post);
  System.out.println("\nSending 'POST' request to URL : " + url);
  System.out.println("Post parameters : " + post.getEntity());
  System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

  BufferedReader rd =
      new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

  StringBuffer result = new StringBuffer();
  String line = "";
  while ((line = rd.readLine()) != null) {
    result.append(line);
  }

  ObjectMapper mapper = new ObjectMapper();

  // read JSON from a file
  Map<String, Object> map =
      mapper.readValue(result.toString(), new TypeReference<Map<String, Object>>() {});

  assertTrue(map.containsKey("data"));
  Map<String, Object> data = pullOutNestedData(map);
  assertEquals("John Smith", data.get("value"));
}
 
Example 20
Source File: HttpComponentsHttpInvokerRequestExecutor.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Execute the given HttpPost instance.
 * @param config the HTTP invoker configuration that specifies the target service
 * @param httpClient the HttpClient to execute on
 * @param httpPost the HttpPost to execute
 * @return the resulting HttpResponse
 * @throws java.io.IOException if thrown by I/O methods
 */
protected HttpResponse executeHttpPost(
		HttpInvokerClientConfiguration config, HttpClient httpClient, HttpPost httpPost)
		throws IOException {

	return httpClient.execute(httpPost);
}