【问题标题】:HttpURLConnection POST parameters does not work correctlyHttpURLConnection POST 参数无法正常工作
【发布时间】:2016-03-08 17:18:56
【问题描述】:

我使用 POST 请求和参数创建了 HttpURLConnection 以发送到服务器。服务器响应:

违反完整性约束:列“operator_id”不能为空

但我清楚地在查询中发送了它。我尝试通过终端使用 curl,它工作正常。服务器接受查询并将其保存到数据库。我匹配 curl 和 Android 调用中的所有参数值,但没有帮助。

这里是 AsyncTask 类。

public class HttpPost extends AsyncTask<String, String, String> {
  Context context;
  public HttpPost (Context context){
    this.context = context;
  }
   @Override
protected String doInBackground(String... params) {
    URL url;
    String response = "";
    try {
            url = new URL(params[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            String query = "operator_id=1&date=*********";
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();

            int responseCode = conn.getResponseCode();
            .......
            conn.disconnect();
    catch ( Exception e){
      e.printStackTrace();
    }
    return response;
}

这是 curl 调用

curl -H "Content-Type: application/json" -X POST -d '{"operator_id":1,"date":"",other value...}'  https://www.mywebsite.com/

有人知道我做错了什么吗?

【问题讨论】:

    标签: android https http-post


    【解决方案1】:

    尝试将字符串参数包装在有效的 JSON 中应该可以。

    String query = "{\"operator_id\":1,\"date\":\"*********\"}";
    

    【讨论】:

    • 天哪。我认为查询是附加到网址。它现在正在工作。谢谢。
    • 有点好奇,因为你在 curl 调用中做对了!
    猜你喜欢
    • 2017-03-10
    • 1970-01-01
    • 2015-09-27
    • 2014-02-22
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多