我正在使用 Apache httpcomponents 实现彗星式(延迟响应)http 服务器。我的代码与http://hc.apache.org/httpcomponents-core-ga/examples.html上的“基本非阻塞 HTTP 服务器”示例非常相似
我使用 DefaultServerIOEventDispatch 和 DefaultListeningIOReactor 来调度请求,就像在示例代码中一样。在我的 NHttpRequestHandler 中,我想记录每个请求的 IP 地址。
在 HttpRequestHandler 中,您可以访问 HttpRequest、HttpResponse 和 HttpContext。使用 NHttpRequestHandler,您还有一个 NHttpResponseTrigger。如何获取请求来自的远程 IP 地址?我看不出如何使用可用的对象来做到这一点。
更新,这是我最终使用的 Scala 代码:
def getIp(context: HttpContext): Option[String] = {
val conn = context.getAttribute(ExecutionContext.HTTP_CONNECTION)
conn match {
case inet: HttpInetConnection =>
inet.getRemoteAddress match {
case sock: java.net.InetSocketAddress => // HttpComponents 4.1
Some(sock.getAddress.getHostAddress)
case adr: java.net.InetAddress => // HttpComponents 4.2
Some(adr.getHostAddress)
case unknown =>
Some(unknown.toString)
}
case _ => None
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,HttpComponents …
如何在Apache HTTP组件中设置字符编码?
我做这样的事情:
Form form = Form.form();
form = form.add("somekey", "somevalue");
Request request = Request.Post("http://somehost/some-form")
.request.bodyForm(form.build());
Run Code Online (Sandbox Code Playgroud)
"somekey"和"somevalue"是unicode字符串,因为所有java字符串都是unicode.我测试时,http组件将它们转换为latin-1.我希望它转换为其他东西(例如,utf-8).
当尝试在Apache Karaf OSGi容器中安装httpclient-osgi 4.3.2软件包(org.apache.httpcomponents:httpclient-osgi:bundle:4.3.2,如HC站点上指定)时,我收到以下错误报告:
karaf@root> install mvn:org.apache.httpcomponents/httpclient-osgi/4.3.2
Bundle ID: 60
karaf@root> start 60
Error executing command: Error starting bundles:
Unable to start bundle 60: Unresolved constraint in bundle
org.apache.httpcomponents.httpclient [60]: Unable to resolve 60.0:
missing requirement [60.0] osgi.wiring.package;
(&(osgi.wiring.package=org.apache.http.concurrent)(version>=4.3.0)
(!(version>=4.4.0)))
Run Code Online (Sandbox Code Playgroud)
在检查标头时,似乎它尝试加载的依赖项被标记为Private-Package,并且可以在包JAR中找到类:
karaf@root> headers 60
Run Code Online (Sandbox Code Playgroud)
=>
...
Private-Package =
org.apache.commons.codec,
org.apache.commons.codec.binary,
org.apache.commons.codec.digest,
org.apache.commons.codec.language,
org.apache.commons.codec.language.bm,
org.apache.commons.codec.net,
org.apache.http,
org.apache.http.annotation,
org.apache.http.concurrent,
org.apache.http.config,
org.apache.http.entity,
org.apache.http.impl,
org.apache.http.impl.entity,
org.apache.http.impl.io,
org.apache.http.impl.pool,
org.apache.http.io,
org.apache.http.message,
org.apache.http.osgi.impl,
org.apache.http.params,
org.apache.http.pool,
org.apache.http.protocol,
org.apache.http.util
Run Code Online (Sandbox Code Playgroud)
同时,org.apache.http*也被定义为Import-Package …
我正在用春天和cglib运行硒.
我收到此错误:java.lang.ClassNotFoundException:org.apache.http.config.RegistryBuilder
但我无法找到相关的包裹在哪里!有人可以帮忙吗?
谢谢
我需要设置一个具有SSL支持的Apache HTTPAsyncClient。我使用此代码,但是它似乎不起作用(获取“ javax.net.ssl.SSLException:收到致命警报:handshake_failure”)
System.setProperty("javax.net.debug", "ssl,handshake");
System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
KeyStore ts = KeyStore.getInstance("JKS");
ts.load(loadStream("C:/TrustStore/cacerts"), "trustpass".toCharArray());
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(loadStream("C:/KeyStore/SSL/keystore.SomeKey"), "keypass".toCharArray());
SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(ts).loadKeyMaterial(ks, "somekey".toCharArray()).setSecureRandom(new SecureRandom());
SSLContext ssl = sslBuilder.build();
PoolingNHttpClientConnectionManager cm = new PoolingNHttpClientConnectionManager(new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT));
CloseableHttpAsyncClient clientHttps = HttpAsyncClientBuilder.create()
.setConnectionManager(cm)
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
.setSSLContext(ssl)
.build();
RequestConfig.Builder b = RequestConfig.custom();
b.setProxy(new HttpHost("proxyHost", proxyPort));
RequestConfig rc = b.build();
clientHttps.start();
HttpRequestBase req = new HttpPost("https://someurl");
((HttpEntityEnclosingRequestBase)req).setEntity(new StringEntity("somestring"));
req.setConfig(rc);
clientHttps.execute(req, new FutureCallback<HttpResponse>() {
@Override
public void failed(Exception ex) {
System.out.println(ex);
}
@Override
public void completed(HttpResponse result) …Run Code Online (Sandbox Code Playgroud) 我使用Apache HttpClient通过MultipartEntity上传文件,我需要上传不同文件名的文件..下面是我的代码...
FileBody uploadFilePart = new FileBody(binaryFile);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", uploadFilePart);
reqEntity.addPart("comment", comment);
httpPost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println("Response content length: " +
resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
Run Code Online (Sandbox Code Playgroud)
帮助感谢!
谢谢,Surez
我想做这个:
Content result = Request
.Get("url.com")
.addHeader("CookieName", "CookieValue") // is this the proper way ?
.execute()
.returnContent();
Run Code Online (Sandbox Code Playgroud)
与org.apache.http.client.fluent.Request.这是Apache HTTP Components的一部分.
我似乎无法在文档中找到它,对此感到抱歉并感谢您的帮助.
我知道我可以使用setParameter方法添加http参数,但是如何使用URIBuilder该类将正文传递给http请求?
例如这个
URI uri = new URIBuilder().setScheme("http")
.setHost("localhost:9091/test").setParameter("a", "1")
.setParameter("b", "2").build();
Run Code Online (Sandbox Code Playgroud)
等效于以下curl请求:
curl -X POST http://localhost:9091/test\?a\=1\&b\=2
但是如何URIBuilder针对以下curl 使用(或任何其他类)构建URL :
curl -X POST http://localhost:9091/test -d '{"a":1,"b":2}'
apache curl http apache-httpcomponents apache-httpclient-4.x
我已经构建了一个应用程序来插入一个记录,但它编译错误,请帮助我我的jasonparser类
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {}
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
try {
if (method == "POST") {
DefaultHttpClient httpClient = new DefaultHttpClient(); …Run Code Online (Sandbox Code Playgroud) 我安装了Apache httpcomponents-client-5.0.x,在查看 http 响应的标头时,我很惊讶它没有显示Content-Length和Content-Encoding标头,这是我用于测试的代码
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import com.sun.net.httpserver.Headers;
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet request = new HttpGet(new URI("https://www.example.com"));
CloseableHttpResponse response = httpclient.execute(request);
Header[] responseHeaders = response.getHeaders();
for(Header header: responseHeaders) {
System.out.println(header.getName());
}
// this prints all the headers except
// status code header
// Content-Length
// Content-Encoding
Run Code Online (Sandbox Code Playgroud)
无论我尝试什么,我都会得到相同的结果,就像这样
Iterator<Header> headersItr = response.headerIterator();
while(headersItr.hasNext()) {
Header header = headersItr.next();
System.out.println(header.getName());
}
Run Code Online (Sandbox Code Playgroud)
或这个
HttpEntity entity = response.getEntity();
System.out.println(entity.getContentEncoding()); // NULL
System.out.println(entity.getContentLength()); // …Run Code Online (Sandbox Code Playgroud) java debugging apache-httpcomponents apache-httpclient-4.x apache-httpclient-5.x