从java发布请求到php

时间:2015-03-21 21:30:10

标签: java php http post

我有一个问题,当我从java向web服务器发送一个post请求时。但是当我使用GET方法时,它运行得很好。

java代码

   package networkTest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;

public class Main {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    try {
        URL url=new URL("http://127.0.0.1/index.php");
        HttpURLConnection curl=(HttpURLConnection) url.openConnection();
        curl.setDoInput(true);
        curl.setDoOutput(true);
        curl.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
        curl.setAllowUserInteraction(true);

        curl.setRequestMethod("POST"); //**
        OutputStream out =curl.getOutputStream();
        InputStream in =curl.getInputStream();
        String data="name=xxx";
        out.write(data.getBytes());

        InputStreamReader reader=new InputStreamReader(in);
        BufferedReader Breader=new BufferedReader(reader);
        String buff;
        String Rdata="";
        while((buff=Breader.readLine()) !=null )
        {
            Rdata+=buff+"\n";
        }
        System.out.println(Rdata);




    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        System.err.println("error in url connection");
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.err.println("IO execption: error in opening connection");
        e.printStackTrace();
    }



  }
}

PHP代码 我收到inputstream的回复,但$ _POST [“名称”]总是未设置,响应总是“没有请求”

<?php
    if(isset($_POST["name"]))
    {
        echo($_POST["name"]);
    }
    else
    {
        echo"there is no request";
    }
?>

0 个答案:

没有答案