【问题标题】:re-write php post request to java Android post request (and get response)将php post请求重写为java Android post请求(并获得响应)
【发布时间】:2017-09-16 14:16:41
【问题描述】:

我想从 android 应用程序创建这个 post 请求,并获得 json 响应:

function send_post_to_url($url,$post) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch,CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
    $return = curl_exec($ch);
    curl_close($ch);
    return $return;
}

$data['api_key'] = YOUR_API_KEY;
$data['action'] = 'TestFunction';
$response = send_post_to_url('https://api.superget.co.il/',$data);
echo $response;

我该怎么做?

我尝试了以下方法,但 connect 不断抛出异常

        HttpURLConnection urlConnection;
        urlConnection = (HttpURLConnection) ((new URL("https://api.superget.co.il").openConnection()));
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.connect();

【问题讨论】:

标签: java php android curl post


【解决方案1】:

试试我的代码:

sendPost 方法:

public boolean sendPost(Map<String, Object> params, String urlAddress) {

        URL url;
        HttpURLConnection urlConnection = null;

        try {

            StringBuilder postData = new StringBuilder();
            for (Map.Entry<String, Object> param : params.entrySet()) {
                if (postData.length() != 0) postData.append('&');
                postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                postData.append('=');
                postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
            }
            byte[] postDataBytes = postData.toString().getBytes("UTF-8");

            url = new URL(urlAddress);
            urlConnection = (HttpURLConnection) url.openConnection();


            //urlConnection.setReadTimeout(10000 /* milliseconds */);
            //urlConnection.setConnectTimeout(15000 /* milliseconds */);

            //add reuqest header
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            urlConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
            urlConnection.setRequestProperty("charset", "utf-8");

            //urlConnection.setUseCaches( false );
            //urlConnection.setInstanceFollowRedirects( false );


            urlConnection.setDoOutput(true);
            // Send post request
            DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
            wr.write(postDataBytes); //wr.writeBytes(postData.toString());
            wr.flush();
            wr.close();
            //urlConnection.getOutputStream().write(postDataBytes);

            /*
            int responseCode = urlConnection.getResponseCode();
            Log.e("ddd", "\nSending 'POST' request to URL : " + url);
            Log.e("ddd", "Post parameters : " + postData.toString());
            Log.e("ddd", "Response Code : " + responseCode); */


            String response = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            String inputLine;
            while ((inputLine = in.readLine()) != null)
                response += inputLine;
            in.close();

            //get response
            return response.trim().equals("ok");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null)
                urlConnection.disconnect();
        }

        return false;
    }

使用:

Map<String, Object> params = new HashMap<>();
params.put("param1", txtContactNf.getText().toString());
params.put("param2", txtContactNf.getText().toString());
final boolean successSend = nu.sendPost(params, "http://yoursite.com/api.php");

在这段代码中,如果 php 脚本说 ok 那么我们得到 true 布尔结果。您可以轻松更改它并获取 json 结果。

编辑:获取 json 结果

改为return response.trim().equals("ok");

String response = "";
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String inputLine;
while ((inputLine = in.readLine()) != null)
response += inputLine;
in.close();

if(response.equals("no")) return null;

return new JSONObject(response);

返回类型必须是 JSONObject

【讨论】:

  • 这对我不起作用,在使用“action”初始化 Map 实例后,我从服务器收到了他无法识别我的操作的响应
  • @AndoridBegginer 什么是响应结果?敬酒或登录response 并告诉我。
猜你喜欢
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-13
  • 1970-01-01
  • 2020-11-17
  • 2017-09-25
  • 2017-08-06
相关资源
最近更新 更多