![](/img/trans.png)
[英]Jersey http client: put request with custom Content-Length
[英]jersey http client custom request method
使用以下代碼,使用jersey
:
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-apache-client4</artifactId>
<version>1.13-b01</version>
我有使用自定義請求方法的問題,如FOOBAR,PATCH,SEARCH等。在httpUrlConnection
不存在。
DefaultClientConfig config = new DefaultClientConfig();
config.getProperties().put(URLConnectionClientHandler.PROPERTY_HTTP_URL_CONNECTION_SET_METHOD_WORKAROUND, true);
Client c = Client.create(config);
Form f = new Form();
f.add("id", "foobar");
WebResource r = c.resource("http://127.0.0.1/foo");
String methodName = "foobar";
String response = r.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept(MediaType.APPLICATION_JSON_TYPE).header("USER-AGENT", "my-java-sdk /1.1").method(methodName.toUpperCase(), String.class, f);
結果是以下異常:
com.sun.jersey.api.client.ClientHandlerException: java.net.ProtocolException: Invalid HTTP method: FOOBAR
我已經嘗試了各種方法來嘗試解決這個問題,但沒有成功。
config.getProperties()
行中實現了。 仍然收到錯誤 長話短說,我想實現類似於via Java中提供的功能:
提前感謝您的反饋
使用Jersey 2.x Client
,我們將設置該屬性
為true
Client client = ClientBuilder.newClient();
client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
String response = client.target(url).request().method("PATCH", entity, String.class);
它不是一個bug,它是一個功能。 :)
不過實話說。 HttpUrlConnection不允許您使用自定義HTTP方法,因為:
//此限制將阻止人們使用此類
//使用java實驗w / new HTTP方法。
所以你不能使用其他方法(在java 6中):“GET”,“POST”,“HEAD”,“OPTIONS”,“PUT”,“DELETE”,“TRACE”
Jersey提供了一種解決方法,它使用反射來省略此檢查:
DefaultClientConfig config = new DefaultClientConfig();
config.getProperties().put(URLConnectionClientHandler.PROPERTY_HTTP_URL_CONNECTION
_SET_METHOD_WORKAROUND, true);
Client c = Client.create(config);
WebResource r = c.resource("http://google.com");
String reponse = r.method("FOOBAR", String.class);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.