我正在使用HTTPServer包提供的com.sun.net.httpserver.HttpServer编写一个服务。我需要将一些相当大的数据作为字节流发送到这个服务(比如一百万整数)。
我几乎搜索了所有可用的示例,都指向在URL中发送一个小的GET请求。我需要知道如何将数据作为POST请求发送。另外,是否对可以发送的数据有任何限制?
发布于 2014-10-14 08:30:04
与上述答案中的持久URL连接不同,我建议使用Apache HTTPClient库(如果您不使用通信)。
http://hc.apache.org/httpclient-3.x/
在这种情况下,您可以构建一个客户机并将一个序列化对象(例如序列化为JSON:https://code.google.com/p/google-gson/ )作为POST请求通过HTTP发送到您的服务器:
public HttpResponse sendStuff (args) {
HttpPost post = null;
try {
HttpClient client = HttpClientBuilder.create().build();
post = new HttpPost(servletUrl);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(<nameString>, <valueString>));
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
response.getStatusLine().getStatusCode();
return response;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}然而,Spring为您节省了大量的时间和麻烦,所以我推荐给看看这个
发布于 2014-10-14 08:49:45
您可以通过将字节写入连接输出流来发送POST请求的数据,如下所示
public static String excutePost(String targetURL, String urlParameters)
{
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}对于POST,可以发送的数据量没有限制。您可以了解有关GET here HTTP GET请求的最大长度?的限制的详细信息。
发布于 2014-10-14 07:40:20
如果我说得对,您希望按照HTTPServer的方向发送请求,作为GET请求,而不是使用post。
在HTTP客户端实现中,可以设置HTTP头和请求方法:
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("GET"); //Or POST
} catch (IOException e) {
e.printStacktrace();
}https://stackoverflow.com/questions/26355138
复制相似问题