Java Code Examples for org.apache.http.HttpResponse

The following are top voted examples for showing how to use org.apache.http.HttpResponse. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: yacy_grid_mcp   File: ClientConnection.java   Source Code and License 14 votes vote down vote up
/**
 * get a redirect for an url: this method shall be called if it is expected that a url
 * is redirected to another url. This method then discovers the redirect.
 * @param urlstring
 * @param useAuthentication
 * @return the redirect url for the given urlstring
 * @throws IOException if the url is not redirected
 */
public static String getRedirect(String urlstring) throws IOException {
    HttpGet get = new HttpGet(urlstring);
    get.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build());
    get.setHeader("User-Agent", ClientIdentification.getAgent(ClientIdentification.yacyInternetCrawlerAgentName).userAgent);
    CloseableHttpClient httpClient = getClosableHttpClient();
    HttpResponse httpResponse = httpClient.execute(get);
    HttpEntity httpEntity = httpResponse.getEntity();
    if (httpEntity != null) {
        if (httpResponse.getStatusLine().getStatusCode() == 301) {
            for (Header header: httpResponse.getAllHeaders()) {
                if (header.getName().equalsIgnoreCase("location")) {
                    EntityUtils.consumeQuietly(httpEntity);
                    return header.getValue();
                }
            }
            EntityUtils.consumeQuietly(httpEntity);
            throw new IOException("redirect for  " + urlstring+ ": no location attribute found");
        } else {
            EntityUtils.consumeQuietly(httpEntity);
            throw new IOException("no redirect for  " + urlstring+ " fail: " + httpResponse.getStatusLine().getStatusCode() + ": " + httpResponse.getStatusLine().getReasonPhrase());
        }
    } else {
        throw new IOException("client connection to " + urlstring + " fail: no connection");
    }
}
 
Example 2
Project: safecharge-java   File: SafechargeRequestExecutor.java   Source Code and License 12 votes vote down vote up
/**
 * Sends a POST request to the service at {@code serviceUrl} with a payload of {@code request}.
 * The request type is determined by the {@code headers} param.
 *
 * @param request    A {@link String} representation of a request object. Can be JSON object, form data, etc...
 * @param serviceUrl The service URL to sent the request to
 * @param headers    An array of {@link Header} objects, used to determine the request type
 * @return {@link String} response from the service (representing JSON object)
 * @throws IOException if the connection is interrupted or the response is unparsable
 */
public String executeRequest(String request, String serviceUrl, Header[] headers) throws IOException {
    HttpPost httpPost = new HttpPost(serviceUrl);
    httpPost.setHeaders(headers);
    httpPost.setEntity(new StringEntity(request, Charset.forName("UTF-8")));

    if (logger.isDebugEnabled()) {
        logger.debug("Sent " + request);
    }

    HttpResponse response = httpClient.execute(httpPost);

    String responseJSON = EntityUtils.toString(response.getEntity(), UTF8_CHARSET);
    if (logger.isDebugEnabled()) {
        logger.debug("Received " + responseJSON);
    }
    return responseJSON;
}
 
Example 3
Project: weixinpay   File: HttpUtil.java   Source Code and License 9 votes vote down vote up
public static String postUrl(String url, String body) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    httppost.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET, "UTF-8");

    //请求超时 ,连接超时
    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
    //读取超时
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);


    try {
        StringEntity entity = new StringEntity(body, "UTF-8");
        httppost.setEntity(entity);

        System.out.println(entity.toString());

        HttpResponse response = httpclient.execute(httppost);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String charsetName = EntityUtils.getContentCharSet(response.getEntity());
            //System.out.println(charsetName + "<<<<<<<<<<<<<<<<<");

            String rs = EntityUtils.toString(response.getEntity());
            //System.out.println( ">>>>>>" + rs);

            return rs;
        } else {
            //System.out.println("Eorr occus");
        }
    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    return "";
}
 
Example 4
Project: sjk   File: CatalogConvertorControllerTest.java   Source Code and License 8 votes vote down vote up
@Test
public void testEdit() throws URISyntaxException, ClientProtocolException, IOException {
    String url = "http://127.0.0.1:8080/sjk-market-admin/admin/catalogconvertor/edit.json";
    URIBuilder urlb = new URIBuilder(url);

    // 参数
    urlb.setParameter("id", "1");
    urlb.setParameter("marketName", "eoemarket");
    urlb.setParameter("catalog", "1");
    urlb.setParameter("subCatalog", "15");
    urlb.setParameter("subCatalogName", "系统工具1");
    urlb.setParameter("targetCatalog", "1");
    urlb.setParameter("targetSubCatalog", "14");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(urlb.build());
    HttpResponse response = httpClient.execute(httpPost);
    logger.debug("URL:{}\n{}\n{}", url, response.getStatusLine(), response.getEntity());
}
 
Example 5
Project: elasticjob-stock-push   File: HttpUtils.java   Source Code and License 8 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 6
Project: elasticjob-oray-client   File: HttpUtils.java   Source Code and License 8 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 7
Project: Zmap_test   File: SearchPageActivity.java   Source Code and License 6 votes vote down vote up
/**
 * 清除远端搜索数据
 */
private void sendRequestWithHttpClient_clearHistory() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            HttpClient httpCient = new DefaultHttpClient();  //创建HttpClient对象
            HttpGet httpGet = new HttpGet(url + "/history.php?action=clearSearchHistory&id=" + current_user.getUser_id()
                    + "&username=" + current_user.getUsername());
            try {
                HttpResponse httpResponse = httpCient.execute(httpGet);//第三步:执行请求,获取服务器发还的相应对象
                if ((httpResponse.getEntity()) != null) {
                    HttpEntity entity = httpResponse.getEntity();
                    //TODO 处理返回值
                    String response = EntityUtils.toString(entity, "utf-8");//将entity当中的数据转换为字符串
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}
 
Example 8
Project: BUbiNG   File: Filters.java   Source Code and License 6 votes vote down vote up
/** Adapts a filter with {@link HttpResponse} base type to a filter with {@link FetchData} base type.
 *
 * @param original the original filter.
 * @return the adapted filter.
 */
public static Filter<FetchData> adaptFilterHttpResponse2FetchData(final Filter<HttpResponse> original) {
	return new AbstractFilter<FetchData>() {
		@Override
		public boolean apply(FetchData x) {
			return original.apply(x.response());
		}
		@Override
		public String toString() {
			return original.toString();
		}
		@Override
		public Filter<FetchData> copy() {
			return adaptFilterHttpResponse2FetchData(original.copy());
		}
	};
}
 
Example 9
Project: pyroclast-java   File: ReadCommitParser.java   Source Code and License 6 votes vote down vote up
@Override
public ReadCommitResult parseResponse(HttpResponse response, ObjectMapper mapper) throws IOException, PyroclastAPIException {
    int status = response.getStatusLine().getStatusCode();

    switch (status) {
        case 200:
            return new ReadCommitResult(true);
        case 400:
            throw new MalformedEventException();

        case 401:
            throw new UnauthorizedAccessException();

        default:
            throw new UnknownAPIException(response.getStatusLine().toString());
    }
}
 
Example 10
Project: wechat-mall   File: AsynHttpClient.java   Source Code and License 6 votes vote down vote up
public static Future<HttpResponse> POST(String url, FutureCallback<HttpResponse> callback,
        List<NameValuePair> params, String encoding, Map<String, String> headers) {
    HttpPost post = new HttpPost(url);
    headers.forEach((key, value) -> {
        post.setHeader(key, value);
    });
    HttpEntity entity = new UrlEncodedFormEntity(params, HttpClientUtil.getEncode(encoding));
    post.setEntity(entity);
    return HTTP_CLIENT.execute(post, callback);
}
 
Example 11
Project: boohee_v5.6   File: d.java   Source Code and License 6 votes vote down vote up
private static boolean a(HttpResponse httpResponse) {
    String str = null;
    String str2 = a;
    if (httpResponse != null) {
        Header[] allHeaders = httpResponse.getAllHeaders();
        if (allHeaders != null && allHeaders.length > 0) {
            for (Header header : allHeaders) {
                if (header != null) {
                    String name = header.getName();
                    if (name != null && name.equalsIgnoreCase(str2)) {
                        str = header.getValue();
                        break;
                    }
                }
            }
        }
    }
    return Boolean.valueOf(str).booleanValue();
}
 
Example 12
Project: hustic   File: GetResponseHandler.java   Source Code and License 6 votes vote down vote up
@Override
public GetResponse handleResponse(HttpResponse httpResponse) throws IOException {
    int code = httpResponse.getStatusLine().getStatusCode();
    GetResponse getResponse = new GetResponse(code);
    if (code != 200) {

    }

    InputStream content = httpResponse.getEntity().getContent();
    JsonObject responseJson = Json.createReader(content).readObject();
    boolean isFound = responseJson.getBoolean("found");
    if (!isFound) {
        return getResponse;
    }

    getResponse.setData(getData(responseJson));
    return getResponse;
}
 
Example 13
Project: letv   File: HttpTask.java   Source Code and License 6 votes vote down vote up
protected void sendResponseMessage(HttpResponse response) {
    super.sendResponseMessage(response);
    Header[] headers = response.getHeaders("Set-Cookie");
    if (headers != null && headers.length > 0) {
        CookieSyncManager.createInstance(this.val$context).sync();
        CookieManager instance = CookieManager.getInstance();
        instance.setAcceptCookie(true);
        instance.removeSessionCookie();
        String mm = "";
        for (Header header : headers) {
            String[] split = header.toString().split("Set-Cookie:");
            EALogger.i("正式登录", "split[1]===>" + split[1]);
            instance.setCookie(Constants.THIRDLOGIN, split[1]);
            int index = split[1].indexOf(";");
            if (TextUtils.isEmpty(mm)) {
                mm = split[1].substring(index + 1);
                EALogger.i("正式登录", "mm===>" + mm);
            }
        }
        EALogger.i("正式登录", "split[1222]===>COOKIE_DEVICE_ID=" + LemallPlatform.getInstance().uuid + ";" + mm);
        instance.setCookie(Constants.THIRDLOGIN, "COOKIE_DEVICE_ID=" + LemallPlatform.getInstance().uuid + ";" + mm);
        instance.setCookie(Constants.THIRDLOGIN, "COOKIE_APP_ID=" + LemallPlatform.getInstance().getmAppInfo().getId() + ";" + mm);
        CookieSyncManager.getInstance().sync();
        this.val$iLetvBrideg.reLoadWebUrl();
    }
}
 
Example 14
Project: lams   File: HttpAuthenticator.java   Source Code and License 6 votes vote down vote up
public boolean isAuthenticationRequested(
        final HttpHost host,
        final HttpResponse response,
        final AuthenticationStrategy authStrategy,
        final AuthState authState,
        final HttpContext context) {
    if (authStrategy.isAuthenticationRequested(host, response, context)) {
        return true;
    } else {
        switch (authState.getState()) {
        case CHALLENGED:
        case HANDSHAKE:
            authState.setState(AuthProtocolState.SUCCESS);
            authStrategy.authSucceeded(host, authState.getAuthScheme(), context);
            break;
        case SUCCESS:
            break;
        default:
            authState.setState(AuthProtocolState.UNCHALLENGED);
        }
        return false;
    }
}
 
Example 15
Project: chatbot   File: QANARY.java   Source Code and License 6 votes vote down vote up
private String makeRequest(String question) {
        try {
            HttpPost httpPost = new HttpPost(URL);
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("query", question));
//            params.add(new BasicNameValuePair("lang", "it"));
            params.add(new BasicNameValuePair("kb", "dbpedia"));

            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, Consts.UTF_8);
            httpPost.setEntity(entity);

            HttpResponse response = client.execute(httpPost);

            // Error Scenario
            if(response.getStatusLine().getStatusCode() >= 400) {
                logger.error("QANARY Server could not answer due to: " + response.getStatusLine());
                return null;
            }

            return EntityUtils.toString(response.getEntity());
        }
        catch(Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }
 
Example 16
Project: android-advanced-light   File: MainActivity.java   Source Code and License 6 votes vote down vote up
/**
 * 使用HttpClient的get请求网络
 *
 * @param url
 */

private void useHttpClientGet(String url) {
    HttpGet mHttpGet = new HttpGet(url);
    mHttpGet.addHeader("Connection", "Keep-Alive");
    try {
        HttpClient mHttpClient = createHttpClient();
        HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
        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 17
Project: GitHub   File: OkApacheClientTest.java   Source Code and License 6 votes vote down vote up
@Test public void contentEncoding() throws Exception {
  String text = "{\"Message\": { \"text\": \"Hello, World!\" } }";
  server.enqueue(new MockResponse().setBody(gzip(text))
      .setHeader("Content-Encoding", "gzip"));

  HttpGet request = new HttpGet(server.url("/").url().toURI());
  request.setHeader("Accept-encoding", "gzip"); // Not transparent gzip.
  HttpResponse response = client.execute(request);
  HttpEntity entity = response.getEntity();

  Header[] encodingHeaders = response.getHeaders("Content-Encoding");
  assertEquals(1, encodingHeaders.length);
  assertEquals("gzip", encodingHeaders[0].getValue());
  assertNotNull(entity.getContentEncoding());
  assertEquals("gzip", entity.getContentEncoding().getValue());

  assertEquals(text, gunzip(entity));
}
 
Example 18
Project: marklogic-rdf4j   File: ConnectedRESTQA.java   Source Code and License 6 votes vote down vote up
public static void deleteRESTUser(String usrName){
	try{
		DefaultHttpClient client = new DefaultHttpClient();

		client.getCredentialsProvider().setCredentials(
				new AuthScope(host, 8002),
				new UsernamePasswordCredentials("admin", "admin"));

		HttpDelete delete = new HttpDelete("http://"+host+":8002/manage/v2/users/"+usrName);

		HttpResponse response = client.execute(delete);
		if(response.getStatusLine().getStatusCode()== 202){
			Thread.sleep(3500);
		}
	}catch (Exception e) {
		// writing error to Log
		e.printStackTrace();
	}

}
 
Example 19
Project: Tenable.io-SDK-for-Java   File: HttpFuture.java   Source Code and License 6 votes vote down vote up
private LogInstance logResponse( LogInstance logInstance, HttpResponse response, String respBody ) {
    if( response != null ) {
        logInstance.setRespHttpStatus( response.getStatusLine().getStatusCode() );

        // log request headers and body?
        for( Header header : response.getAllHeaders() ) {
            if( logLevel == LogLevel.TRACE || header.getName().toLowerCase().equals( "x-gateway-site-id" ) || header.getName().toLowerCase().equals( "x-request-uuid" ) ) {
                logInstance.addRespHeader( header.getName(), header.getValue() );
            }
        }

        if( logLevel == LogLevel.TRACE ) {
            if( respBody != null ) {
                String logRespBody;
                if( respBody.length() > REQUEST_AND_RESPONSE_BODY_LOG_MAX_LENGTH ) {
                    logRespBody = respBody.substring( 0, REQUEST_AND_RESPONSE_BODY_LOG_MAX_LENGTH ) + "...response body truncated...";
                }
                else logRespBody = respBody;

                logInstance.setRespBody( logRespBody );
            }
       }
    }
    return logInstance;
}
 
Example 20
Project: bootstrap   File: ExceptionMapperIT.java   Source Code and License 6 votes vote down vote up
/**
 * @see ExceptionMapperResource#throwEntityNotFoundException()
 */
@Test
public void testEntityNotFoundException() throws IOException {
	final HttpDelete httpdelete = new HttpDelete(BASE_URI + RESOURCE + "/entityNotFoundException");
	HttpResponse response = null;
	try {
		response = httpclient.execute(httpdelete);
		Assert.assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatusLine().getStatusCode());
		final String content = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
		final Map<?, ?> result = new ObjectMapperTrim().readValue(content, HashMap.class);
		Assert.assertEquals("entity", result.get("code"));
		Assert.assertEquals("key", result.get("message"));
		Assert.assertNull(result.get("cause"));
	} finally {
		if (response != null) {
			response.getEntity().getContent().close();
		}
	}
}
 
Example 21
Project: boohee_v5.6   File: AsyncHttpResponseHandler.java   Source Code and License 6 votes vote down vote up
public void sendResponseMessage(HttpResponse response) throws IOException {
    if (!Thread.currentThread().isInterrupted()) {
        StatusLine status = response.getStatusLine();
        byte[] responseBody = getResponseData(response.getEntity());
        if (!Thread.currentThread().isInterrupted()) {
            if (status.getStatusCode() >= 300) {
                sendFailureMessage(status.getStatusCode(), response.getAllHeaders(),
                        responseBody, new HttpResponseException(status.getStatusCode(),
                                status.getReasonPhrase()));
            } else {
                sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(),
                        responseBody);
            }
        }
    }
}
 
Example 22
Project: elasticsearch_my   File: RestHighLevelClientTests.java   Source Code and License 6 votes vote down vote up
public void testPerformRequestOnSuccess() throws IOException {
    MainRequest mainRequest = new MainRequest();
    CheckedFunction<MainRequest, Request, IOException> requestConverter = request ->
            new Request("GET", "/", Collections.emptyMap(), null);
    RestStatus restStatus = randomFrom(RestStatus.values());
    HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
    Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
            anyObject(), anyVararg())).thenReturn(mockResponse);
    {
        Integer result = restHighLevelClient.performRequest(mainRequest, requestConverter,
                response -> response.getStatusLine().getStatusCode(), Collections.emptySet());
        assertEquals(restStatus.getStatus(), result.intValue());
    }
    {
        IOException ioe = expectThrows(IOException.class, () -> restHighLevelClient.performRequest(mainRequest,
                requestConverter, response -> {throw new IllegalStateException();}, Collections.emptySet()));
        assertEquals("Unable to parse response body for Response{requestLine=GET / http/1.1, host=http://localhost:9200, " +
                "response=http/1.1 " + restStatus.getStatus() + " " + restStatus.name() + "}", ioe.getMessage());
    }
}
 
Example 23
Project: HttpClientMock   File: HttpClientMockBuilderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void should_add_default_host_to_every_relative_path() throws IOException {
    HttpClientMock httpClientMock = new HttpClientMock("http://localhost:8080");

    httpClientMock.onGet("/login").doReturn("login");
    httpClientMock.onGet("/product/search").doReturn("search");
    httpClientMock.onGet("/logout").doReturn("logout");

    HttpResponse login = httpClientMock.execute(new HttpGet("http://localhost:8080/login"));
    HttpResponse search = httpClientMock.execute(new HttpGet("http://localhost:8080/product/search"));
    HttpResponse logout = httpClientMock.execute(new HttpGet("http://localhost:8080/logout"));

    assertThat(login, hasContent("login"));
    assertThat(search, hasContent("search"));
    assertThat(logout, hasContent("logout"));

}
 
Example 24
Project: living-documentation   File: ConfluenceRestClient.java   Source Code and License 6 votes vote down vote up
<T> T sendRequest(HttpRequestBase httpRequest, Function<HttpResponse, T> responseHandler) {
    CloseableHttpResponse response = null;

    try {

        final String encodedCredentials = "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
        httpRequest.addHeader("Accept", "application/json");
        httpRequest.addHeader("Authorization", encodedCredentials);

        response = this.httpClient.execute(httpRequest, httpContext());

        return responseHandler.apply(response);
    } catch (IOException e) {
        throw new RuntimeException("Request could not be sent" + httpRequest, e);
    } finally {
        try {
            if (response != null) {
                response.close();
            }
        } catch (IOException ignored) {
        }
    }
}
 
Example 25
Project: allure-java   File: AllureHttpClientResponse.java   Source Code and License 6 votes vote down vote up
@Override
public void process(final HttpResponse response,
                    final HttpContext context) throws HttpException, IOException {

    final HttpResponseAttachment.Builder builder = create("Response")
            .withResponseCode(response.getStatusLine().getStatusCode());

    Stream.of(response.getAllHeaders())
            .forEach(header -> builder.withHeader(header.getName(), header.getValue()));

    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    response.getEntity().writeTo(os);

    final String body = new String(os.toByteArray(), StandardCharsets.UTF_8);
    builder.withBody(body);

    final HttpResponseAttachment responseAttachment = builder.build();
    processor.addAttachment(responseAttachment, renderer);
}
 
Example 26
Project: marklogic-rdf4j   File: ConnectedRESTQA.java   Source Code and License 5 votes vote down vote up
public static void detachForest(String dbName, String fName){
	try{
		DefaultHttpClient client = new DefaultHttpClient();

		client.getCredentialsProvider().setCredentials(
				new AuthScope(host, 8002),
				new UsernamePasswordCredentials("admin", "admin"));

		HttpPost post = new HttpPost("http://"+host+":8002"+ "/manage/v2/forests/"+fName);
		//			
		List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
		urlParameters.add(new BasicNameValuePair("state", "detach"));
		urlParameters.add(new BasicNameValuePair("database", dbName));

		post.setEntity(new UrlEncodedFormEntity(urlParameters));

		HttpResponse response = client.execute(post);
		HttpEntity respEntity = response.getEntity();

		if (respEntity != null) {
			// EntityUtils to get the response content
			String content =  EntityUtils.toString(respEntity);
			System.out.println(content);
		}
	}catch (Exception e) {
		// writing error to Log
		e.printStackTrace();
	}	
}
 
Example 27
Project: Wechat-Group   File: Utf8ResponseHandler.java   Source Code and License 5 votes vote down vote up
@Override
public String handleResponse(final HttpResponse response) throws IOException {
  final StatusLine statusLine = response.getStatusLine();
  final HttpEntity entity = response.getEntity();
  if (statusLine.getStatusCode() >= 300) {
    EntityUtils.consume(entity);
    throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
  }
  return entity == null ? null : EntityUtils.toString(entity, Consts.UTF_8);
}
 
Example 28
Project: ts-benchmark   File: InfluxDB.java   Source Code and License 5 votes vote down vote up
@Override
public Status selectMinuteMinByDeviceAndSensor(TsPoint point, Date startTime, Date endTime) {
	HttpClient hc = getHttpClient();
	HttpPost post = new HttpPost(QUERY_URL);
	HttpResponse response = null;
	long costTime = 0L;
	try {
		List<NameValuePair> nameValues = new ArrayList<NameValuePair>();
		String selectSql = "SELECT MIN(value) FROM sensor where device_code='" + point.getDeviceCode()
				+ "' and sensor_code='" + point.getSensorCode() + "' and time>=" + TimeUnit.MILLISECONDS.toNanos(startTime.getTime())
				+ " and time<=" + TimeUnit.MILLISECONDS.toNanos(endTime.getTime()) + " group by time(1m)";
		NameValuePair nameValue = new BasicNameValuePair("q", selectSql);
		nameValues.add(nameValue);
		HttpEntity entity = new UrlEncodedFormEntity(nameValues, "utf-8");
		post.setEntity(entity);
		long startTime1 = System.nanoTime();
		response = hc.execute(post);
		long endTime1 = System.nanoTime();
		costTime = endTime1 - startTime1;
	} catch (Exception e) {
		e.printStackTrace();
		return Status.FAILED(-1);
	}finally{
		closeResponse(response);
		closeHttpClient(hc);
	}
	return Status.OK(costTime);
}
 
Example 29
Project: aws-sdk-java-v2   File: ApacheHttpClient.java   Source Code and License 5 votes vote down vote up
/**
 * Creates and initializes an HttpResponse object suitable to be passed to an HTTP response
 * handler object.
 *
 * @return The new, initialized HttpResponse object ready to be passed to an HTTP response handler object.
 * @throws IOException If there were any problems getting any response information from the
 *                     HttpClient method object.
 */
private SdkHttpFullResponse createResponse(org.apache.http.HttpResponse apacheHttpResponse,
                                           HttpRequestBase apacheRequest) throws IOException {
    return SdkHttpFullResponse.builder()
                              .statusCode(apacheHttpResponse.getStatusLine().getStatusCode())
                              .statusText(apacheHttpResponse.getStatusLine().getReasonPhrase())
                              .content(apacheHttpResponse.getEntity() != null ?
                                               toAbortableInputStream(apacheHttpResponse, apacheRequest) : null)
                              .headers(transformHeaders(apacheHttpResponse))
                              .build();

}
 
Example 30
Project: JAVA-HTTP-SDK   File: HttpDeleteMethod.java   Source Code and License 5 votes vote down vote up
public HttpResponse execute() throws Exception {
	HttpResponse httpResponse = null;
	httpClient = HttpClients.createDefault();
	httpResponse = httpClient.execute(httpRequestBase);
	int statusCode = httpResponse.getStatusLine().getStatusCode();
	if (statusCode != HttpStatus.SC_OK && statusCode != 221) {
		String response = EntityUtils.toString(httpResponse.getEntity());
		logger.error("request failed  status:{}, response::{}",statusCode, response);
		throw new OnenetApiException("request failed: " + response);
	}
	return httpResponse;

}
 
Example 31
Project: sjk   File: MarketAppControllerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testEdit() throws URISyntaxException, ClientProtocolException, IOException {
    String url = "http://127.0.0.1:8080/sjk-market-admin/admin/ijinshan/shift-to-ijinshan.json";
    URIBuilder urlb = new URIBuilder(url);
    // 318840 378460 hiapk 雨夜壁纸桌面主题
    // 318839 378435 hiapk APO极限滑板

    urlb.setParameter("ids", "318840,318839");
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(urlb.build());
    HttpResponse response = httpClient.execute(httpPost);
    logger.debug("URL:{}\n{}\n{}", url, response.getStatusLine(), response.getEntity());
}
 
Example 32
Project: HttpClientMock   File: HttpClientMockBuilderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void checkBody() throws IOException {
    HttpClientMock httpClientMock = new HttpClientMock("http://localhost:8080");

    httpClientMock.onPost("/login")
            .doReturnStatus(500);
    httpClientMock.onPost("/login").withBody(containsString("foo"))
            .doReturnStatus(200);

    HttpResponse badLogin = httpClientMock.execute(new HttpPost("http://localhost:8080/login"));
    HttpResponse correctLogin = httpClientMock.execute(httpPost("http://localhost:8080/login", "foo"));

    assertThat(correctLogin, hasStatus(200));
    assertThat(badLogin, hasStatus(500));
}
 
Example 33
Project: q-mail   File: WebDavStore.java   Source Code and License 5 votes vote down vote up
private void handleUnexpectedRedirect(HttpResponse response, String url) throws IOException {
    if (response.getFirstHeader("Location") != null) {
        // TODO: This may indicate lack of authentication or may alternatively be something we should follow
        throw new IOException("Unexpected redirect during request processing. " +
                "Expected response from: " + url + " but told to redirect to:" +
                response.getFirstHeader("Location").getValue());
    } else {
        throw new IOException("Unexpected redirect during request processing. " +
                "Expected response from: " + url + " but not told where to redirect to");
    }
}
 
Example 34
Project: chatbot   File: LookupService.java   Source Code and License 5 votes vote down vote up
public String search(String query) {
    try {
        String url = "?QueryString=" + Utility.urlEncode(query) + "&MaxHits=" + String.valueOf(maxHits);
        if(queryClass != null) {
            url += "&QueryClass=" + String.valueOf(queryClass);
        }

        HttpGet httpGet = new HttpGet(URL + url);
        httpGet.addHeader("Accept", "application/json");
        HttpResponse response = client.execute(httpGet);

        // Error Scenario
        if(response.getStatusLine().getStatusCode() >= 400) {
            logger.error("Lookup Service could not answer due to: " + response.getStatusLine());
            return null;
        }
        else {
            String entities = EntityUtils.toString(response.getEntity());
            JsonNode entity = new ObjectMapper().readTree(entities).get("results").get(0);
            return entity.get("uri").getTextValue();
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 35
Project: integration-test-helper   File: AomHttpClient.java   Source Code and License 5 votes vote down vote up
/**
 * Get a list of objects for the given query
 *
 * @param moduleName
 *        the modulenname
 * @param dataModelName
 *        the name of the datamodels
 * @param query
 *        ApiOmat query string, may be null to append no query
 * @param additionalRequestHeaders
 *        additional headers to be set
 * @return request object to check status codes and return values
 */
public Response getObjects( String moduleName, String dataModelName, String query,
	Map<String, String> additionalRequestHeaders )
{
	final HttpGet request = new HttpGet(
		this.yambasBase + "apps/" + this.appName + "/models/" + moduleName + "/" + dataModelName +
			( query == null ? "" : "?q=" + query ) );
	setAuthorizationHeader( request );
	request.addHeader( "ContentType", "application/json" );
	request.addHeader( "x-apiomat-apikey", this.apiKey );
	request.addHeader( "x-apiomat-system", this.system.toString( ) );
	request.addHeader( "x-apiomat-sdkVersion", this.sdkVersion );
	if ( additionalRequestHeaders != null )
	{
		additionalRequestHeaders.forEach( ( name, value ) -> request.addHeader( name, value ) );
	}
	try
	{
		final HttpResponse response = this.client.execute( request );
		return new Response( response );
	}
	catch ( final IOException e )
	{
		e.printStackTrace( );
	}
	return null;
}
 
Example 36
Project: JInsight   File: HttpAsyncClientInstrumentationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testHttpGet200() throws Exception {
  Snapshot expectedCounts = tracker.snapshot();
  HttpGet request = new HttpGet(server.getEchoEndpoint());
  tracker.validate(expectedCounts); //validate no metric change here

  expectedCounts.increment("GET", "200");
  HttpResponse response = httpclient.execute(request, null).get();

  debug(response);
  tracker.validate(expectedCounts);
}
 
Example 37
Project: GitHub   File: HttpClientStack.java   Source Code and License 5 votes vote down vote up
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
    addHeaders(httpRequest, additionalHeaders);
    addHeaders(httpRequest, request.getHeaders());
    onPrepareRequest(httpRequest);
    HttpParams httpParams = httpRequest.getParams();
    int timeoutMs = request.getTimeoutMs();
    // TODO: Reevaluate this connection timeout based on more wide-scale
    // data collection and possibly different for wifi vs. 3G.
    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
    HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
    return mClient.execute(httpRequest);
}
 
Example 38
Project: Equella   File: OAuthTest.java   Source Code and License 5 votes vote down vote up
private HttpResponse rawTokenExecute(HttpUriRequest request, String rawToken) throws Exception
{
	final Header tokenHeader = new BasicHeader("X-Authorization", rawToken);
	request.setHeader(tokenHeader);
	request.setHeader("X-Autotest-Key", context.getFullName(""));
	final HttpResponse response = getClient().execute(request);
	EntityUtils.consume(response.getEntity());
	return response;
}
 
Example 39
Project: Equella   File: AbstractItemApiTest.java   Source Code and License 5 votes vote down vote up
protected String[] createStaging(String token) throws IOException
{
	HttpResponse stagingResponse = execute(new HttpPost(context.getBaseUrl() + "api/staging"), true, token);
	assertResponse(stagingResponse, 201, "201 not returned from staging creation");
	ObjectNode stagingJson = (ObjectNode) getEntity(stagingResponse.getLastHeader("Location").getValue(), token);
	String stagingUuid = stagingJson.get("uuid").asText();
	String stagingDirUrl = stagingJson.get("links").get("self").asText();
	return new String[]{stagingUuid, stagingDirUrl};
}
 
Example 40
Project: mtgo-best-bot   File: BotCameraService.java   Source Code and License 5 votes vote down vote up
public Long saveBotCam(BotCamera botCamera) {
    HttpEntity entity = MultipartEntityBuilder
            .create()
            .addPart("file", new ByteArrayBody(botCamera.getScreenShot(), "botSnapshot"))
            .build();

    Long idResponse = -1L;

    try {
        HttpPost httpPost = new HttpPost(apiUrl + BotCameraController.ENDPOINT_ROINT + "/" + botCamera.getPlayerBot().getName());
        httpPost.setEntity(entity);
        HttpResponse response = uploadHttpClient.execute(httpPost);
        ResponseHandler<String> handler = new BasicResponseHandler();

        if(response != null &&
            response.getStatusLine() != null &&
            response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {

            final String rawResult = handler.handleResponse(response);

            idResponse = Long.parseLong(rawResult);
        } else {
            log.error("Failed to upload pictar!");
            log.error("Headers received: " + Arrays.stream(response.getAllHeaders()).map(header -> new String(header.getName() + ": " + header.getValue()))
                                                                                    .reduce("", (result, next) -> System.lineSeparator() + next));
            log.error("Body received: " + System.lineSeparator() + handler.handleResponse(response));
        }
    } catch (IOException e) {
        log.error("Failed to upload pictar!");
        log.error(e.getMessage());
    }

    return idResponse;
}