How to wait for Expect 100-continue response in Java using HttpURLConnection

僤鯓⒐⒋嵵緔 提交于 2019-12-02 10:37:25

问题


I am stuck using HttpURLConnection to make a PUT http request to a web-server. I have some code that will make a PUT request just fine, and I can trivially include the 'Expect 100-continue Request Property' in the headers however try as I might I can't seem to make the function wait for the '100 Continue' response from the server before sending the actual http payload.

I get the following (from Wireshark)

PUT /post/ HTTP/1.1
User-Agent: curl/7.35.0
Accept: */*
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue
Host: somerandomdomain.info
Connection: keep-alive
Content-Length: 17

Some data for you
HTTP/1.1 100 Continue

...rest of web-server response...

I'm sure I am missing something obvious however after googling I have drawn a blank - can anyone help?

Many thanks if so :)

Http PUT code snippet below:

String url =   "http://somerandomdomain.info";
String postJsonData = "Some data for you\n";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

// Setting basic post request  
con.setRequestMethod("PUT");
con.setRequestProperty("User-Agent", "jcurl/7.35.0");
con.setRequestProperty("Accept", "*/*");
con.setRequestProperty("Content-Length", postData.length() + "");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Expect", "100-continue");

// Send post request  
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(postData);
wr.flush();
wr.close();

int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post Data : " + postData);
System.out.println("Response Code : " + responseCode);

BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String output;
StringBuffer response = new StringBuffer();

while ((output = in.readLine()) != null) {
  response.append(output);
}

in.close();

//printing result from response  
System.out.println(response.toString());

回答1:


It's not obvious to me why they designed it this way, but the code that implements the Expect:100 logic is only used if you have called one of setFixedLengthStreamingMode(int contentlen) or the overload for long or setChunkedStreamingMode(int chunklen) before doing getOutputStream. In this case I recommend the first as simplest.



来源:https://stackoverflow.com/questions/41707775/how-to-wait-for-expect-100-continue-response-in-java-using-httpurlconnection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!