欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java 填充 HTTP POST 请求的内容,javapost,通过 URLConnec

来源: javaer 分享于  点击 2050 次 点评:227

Java 填充 HTTP POST 请求的内容,javapost,通过 URLConnec


通过 URLConnection 向 Web 服务器发送 POST 请求,请求的数据可以通过下面代码填充

[Java]代码

import java.io.IOException;import java.io.InputStream;import java.io.OutputStreamWriter;import java.net.MalformedURLException;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 {//Configure and open a connection to the site you will send the request            URL url = new URL("http://www.oschina.net");    URLConnection urlConnection = url.openConnection();    //by setting doOutput property to true we indicate that we will use this urlConnection to write data    urlConnection.setDoOutput(true);   // by setting content-type property to  application/x-www-form-urlencoded we define that  // the data that we intent to write on the request's body consist of  key/value pairs    urlConnection.setRequestProperty("content-type","application/x-www-form-urlencoded");// Get the request's output stream     OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());// write the data to the request body    out.write("message=Hello world");    out.flush();    out.close();//Read server's response    InputStream inputStream = urlConnection.getInputStream();    String encoding = urlConnection.getContentEncoding();    String body = IOUtils.toString(inputStream, encoding);    System.out.println(body);        } catch (IOException ex) {            Logger.getLogger(RequestTest.class.getName()).log(Level.SEVERE, null, ex);        }     }}
相关栏目:

用户点评