当前位置: 首页>>代码示例>>Java>>正文


Java HttpResponse类代码示例

本文整理汇总了Java中org.apache.http.HttpResponse的典型用法代码示例。如果您正苦于以下问题:Java HttpResponse类的具体用法?Java HttpResponse怎么用?Java HttpResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


HttpResponse类属于org.apache.http包,在下文中一共展示了HttpResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: executeRequest

import org.apache.http.HttpResponse; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:SafeChargeInternational,项目名称:safecharge-java,代码行数:28,代码来源:SafechargeRequestExecutor.java

示例2: getRedirect

import org.apache.http.HttpResponse; //导入依赖的package包/类
/**
 * 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");
    }
}
 
开发者ID:yacy,项目名称:yacy_grid_mcp,代码行数:34,代码来源:ClientConnection.java

示例3: postUrl

import org.apache.http.HttpResponse; //导入依赖的package包/类
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 "";
}
 
开发者ID:Yunfeng,项目名称:weixinpay,代码行数:40,代码来源:HttpUtil.java

示例4: testEdit

import org.apache.http.HttpResponse; //导入依赖的package包/类
@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());
}
 
开发者ID:zhaoxi1988,项目名称:sjk,代码行数:20,代码来源:CatalogConvertorControllerTest.java

示例5: doPost

import org.apache.http.HttpResponse; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:JiaXiaohei,项目名称:elasticjob-oray-client,代码行数:31,代码来源:HttpUtils.java

示例6: sendRequestWithHttpClient_clearHistory

import org.apache.http.HttpResponse; //导入依赖的package包/类
/**
 * 清除远端搜索数据
 */
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();
}
 
开发者ID:BoldFei,项目名称:Zmap_test,代码行数:24,代码来源:SearchPageActivity.java

示例7: adaptFilterHttpResponse2FetchData

import org.apache.http.HttpResponse; //导入依赖的package包/类
/** 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());
		}
	};
}
 
开发者ID:LAW-Unimi,项目名称:BUbiNG,代码行数:22,代码来源:Filters.java

示例8: parseResponse

import org.apache.http.HttpResponse; //导入依赖的package包/类
@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());
    }
}
 
开发者ID:PyroclastIO,项目名称:pyroclast-java,代码行数:18,代码来源:ReadCommitParser.java

示例9: POST

import org.apache.http.HttpResponse; //导入依赖的package包/类
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);
}
 
开发者ID:jiumao-org,项目名称:wechat-mall,代码行数:11,代码来源:AsynHttpClient.java

示例10: a

import org.apache.http.HttpResponse; //导入依赖的package包/类
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();
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:20,代码来源:d.java

示例11: handleResponse

import org.apache.http.HttpResponse; //导入依赖的package包/类
@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;
}
 
开发者ID:hustlebar,项目名称:hustic,代码行数:19,代码来源:GetResponseHandler.java

示例12: sendResponseMessage

import org.apache.http.HttpResponse; //导入依赖的package包/类
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();
    }
}
 
开发者ID:JackChan1999,项目名称:letv,代码行数:27,代码来源:HttpTask.java

示例13: isAuthenticationRequested

import org.apache.http.HttpResponse; //导入依赖的package包/类
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;
    }
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:24,代码来源:HttpAuthenticator.java

示例14: makeRequest

import org.apache.http.HttpResponse; //导入依赖的package包/类
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;
    }
 
开发者ID:dbpedia,项目名称:chatbot,代码行数:27,代码来源:QANARY.java

示例15: useHttpClientGet

import org.apache.http.HttpResponse; //导入依赖的package包/类
/**
 * 使用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();
    }
}
 
开发者ID:henrymorgen,项目名称:android-advanced-light,代码行数:25,代码来源:MainActivity.java


注:本文中的org.apache.http.HttpResponse类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。