简单的POST请求/响应方法?

时间:2014-02-26 03:06:36

标签: java

基本上,我想要的是获取PHP页面的文本响应以及我定义的一些POST变量。

那么,将一些POST数据(例如“arg1 = this& arg2 = that”)发送到URL并将响应(内容,而不是标题)作为字符串处理的最简单方法是什么?

1 个答案:

答案 0 :(得分:1)

  

使用HttpUrlConnection使用java发送帖子请求。附上你的所有参数,并在test.php中准备你的回复并返回给发件人。

        import java.io.BufferedReader;
        import java.io.DataOutputStream;
        import java.io.InputStreamReader;
        import java.net.HttpURLConnection;
        import java.net.URL;


        private void sendPost() throws Exception 
        {

                String url = "http://example.com/test.php";
                URL obj = new URL(url);
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();

                //add reuqest header
                con.setRequestMethod("POST");
                con.setRequestProperty("User-Agent", "Mozilla/5.0";);
                con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

                String urlParameters = "para1= xxx & para2=yy";

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

                int responseCode = con.getResponseCode();
                if(responseCode == HTTP_OK)
                {
                System.out.println("\nSending 'POST' request to URL : " + url);
                System.out.println("Post parameters : " + urlParameters);
                System.out.println("Response Code : " + responseCode);

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

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

                //print result
                System.out.println(response.toString());
                    }
               }