用Java写数据到POST请求
HTTP POST请求最常见的用途是发送表单参数到服务器。除了发送表单数据,还可以使用POST的消息Body体发送各种数据(如纯文本、XML文档等)。本文讲述如何用Java将数据写入POST请求的Body体。
-
import java.io.IOException;
-
import java.io.InputStream;
-
import java.io.OutputStreamWriter;
-
import java.net.URL;
-
import java.net.URLConnection;
-
import java.util.logging.Level;
-
import java.util.logging.Logger;
-
import org.apache.commons.io.IOUtils;
-
-
public class RequestTest {
-
public static void main(String[] args){
-
try{
-
-
URL url = new URL("");
-
URLConnection urlConnection = url.openConnection();
-
-
urlConnection.setDoOutput(true);
-
-
urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
-
-
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
-
-
out.write("message = Hello World chszs");
-
out.flush();
-
out.close();
-
-
-
InputStream inputStream = urlConnection.getInputStream();
-
String encoding = urlConnection.getContentEncoding();
-
String body = IOUtils.toString(inputStream, encoding);
-
System.out.println(body);
-
}catch(IOException e){
-
Logger.getLogger(RequestTest.class.getName()).log(Level.SEVERE, null, e);
-
}
-
}
-
}
是不是很简单?
阅读(1872) | 评论(1) | 转发(0) |