本文整理汇总了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;
}
示例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");
}
}
示例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 "";
}
示例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());
}
示例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);
}
示例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();
}
示例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());
}
};
}
示例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());
}
}
示例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);
}
示例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();
}
示例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;
}
示例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();
}
}
示例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;
}
}
示例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;
}
示例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();
}
}