HttpurlConnection发布请求正文php服务器?

时间:2016-10-26 12:04:26

标签: php android http-post httpurlconnection

我有一个带有文件的服务器。php我想用我的应用程序将request发送到服务器我试图这样做但是当我尝试我的服务器时我总是“”在邮递员我得到

  

{“result”:“jfYRsbW17HA3bHtaJdDm”,                         “errorMessage”:“错误”}

我想让我的应用看到那些我发送帖子请求的时候是我的代码:(为什么我会变空)

public class HttpParoonakRequest {


public static String HttpParoonakRequestGetUrl(){


    URL url ;
        HttpURLConnection client = null;
    try {

        url = new URL("myphp");

        client = (HttpURLConnection) url.openConnection();
       client.setRequestMethod("POST");

        client.setRequestProperty("method","get_random_wallpaper");



        client.setDoInput(true);
        client.setDoOutput(true);
        client.connect();
        DataOutputStream wr = new DataOutputStream (
                client.getOutputStream ());

        wr.flush ();
        wr.close ();

        //Get Response
        InputStream is = client.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();

        while((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\n');

        }
        Log.d("hey",response.toString());

        rd.close();

        return response.toString();


    } catch (Exception e) {

        e.printStackTrace();
        return e.getMessage();
    }
    finally {
        if(client != null) // Make sure the connection is not null.
            client.disconnect();
    }



}

并在另一项活动中以这种方式调用它:

 thread = new Thread(new Runnable() {


            @Override
            public void run() {
                try {
                    String abcd = HttpParoonakRequest.HttpParoonakRequestGetUrl();
                    System.out.println("Message1 "+ abcd);

                } catch (Exception e) {

                  e.printStackTrace();
                    e.getMessage();
               }

            }
        });
        thread.start();

1 个答案:

答案 0 :(得分:0)

您以错误的方式传递参数:您应该将client.setRequestProperty("method","get_random_wallpaper")替换为client.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");并通过wr流在请求正文中传递您的参数,如下所示:

                ...    

                client = (HttpURLConnection) url.openConnection();
                client.setRequestMethod("POST");

                client.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                client.setDoInput(true);
                client.setDoOutput(true);
                client.connect();
                DataOutputStream wr = new DataOutputStream(
                        client.getOutputStream());

                wr.write("method=get_random_wallpaper".getBytes());

                wr.flush();
                wr.close();
                ...
相关问题