从Android发送参数化HTTP POST请求

时间:2016-02-21 12:50:12

标签: android json http-post

问题:

我无法从Android设备访问云数据。我正在使用POST方法并期待JSON响应。我相信我得到403(禁止)错误。但我可以使用curl访问相同的数据。所以我相信我做错了什么从而寻求某人的帮助。

背景

这是我想要复制的curl命令字符串。我收到对此命令的有效回复。

curl -X POST --data "token={String}&param1={int}&param2={int}" https://www.example.com/api/dir1/dir2"

下面是android代码。

        String post_url = "https://www.example.com/api/dir1/dir2";
        Thread thread = new Thread(new Runnable() {
        public void run() {
            try {

                String urlParameters = "token={Key-string}&param1={int}&param2={int}";
                byte[] postData = urlParameters.getBytes();
                int postDataLength = postData.length;

                URL url = new URL(post_url);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(10000 /* milliseconds */);
                conn.setConnectTimeout(15000 /* milliseconds */);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Accept", "application/json");
                conn.setRequestProperty("charset", "utf-8");
                conn.setRequestProperty("Content-Length",Integer.toString(postDataLength));
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.connect();

                OutputStream os = conn.getOutputStream();
                os.write(urlParameters.toString().getBytes("UTF-8"));
                os.close();

                InputStream stream = conn.getInputStream();

                BufferedReader in = new BufferedReader( new InputStreamReader(stream ));
                String data = null;
                StringBuffer response = new StringBuffer();

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

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    thread.start();

参考文献:

1 个答案:

答案 0 :(得分:0)

您可以尝试在Postman(谷歌浏览器插件)中拨打电话,然后点击代码链接。 Postman将为您生成多种语言的请求,如PHP,Java,C等。

例如:

添加到您的gradle:

compile 'com.squareup.okhttp3:okhttp:3.5.0'

在某个地方拨打电话:

    new Thread() {
       public void run() {
           makeCall();
       }
    }.start();

创建该类:

    public void makeCall() {

    OkHttpClient client = new OkHttpClient();

    MediaType mediaType = MediaType.parse("application/json");
    RequestBody body = RequestBody.create(mediaType, "{\n   \"param1\":\"data1\"}");
    Request request = new Request.Builder()
            .url("https://your_url_here")
            .post(body)
            .addHeader("content-type", "application/json")
            .addHeader("cache-control", "no-cache")
            .build();

    try {
        Response response = client.newCall(request).execute();

        Log.e("okmsg1", response.toString());
        Log.e("okmsg2", response.message());
        Log.e("okmsg3", response.body().string());

    } catch (IOException e) {
        Log.e("err", e.getMessage());
    }

}