HttpURLConnection POST参数无法正常工作

时间:2015-12-03 22:03:03

标签: android https http-post

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

  

完整性约束违规:列' operator_id'不能为空

但我清楚地在查询中发送了它。我尝试通过终端使用curl,它工作正常。服务器接受查询并将其保存到db。我匹配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 -H "Content-Type: application/json" -X POST -d '{"operator_id":1,"date":"",other value...}'  https://www.mywebsite.com/

任何人都知道我做错了什么?

1 个答案:

答案 0 :(得分:2)

尝试将字符串params包装在有效的JSON中应该有效。

# -*- mode: ruby -*-
# vi: set ft=ruby :

# Specify Vagrant version and Vagrant API version
Vagrant.require_version ">= 1.6.0"
VAGRANTFILE_API_VERSION = "2"
ENV['VAGRANT_DEFAULT_PROVIDER'] = 'docker'

# Create and configure the Docker container(s)
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.synced_folder ".", "/vagrant", disabled: true
  config.vm.provider "docker" do |docker|
    docker.vagrant_vagrantfile = "../docker-host/Vagrantfile"
    docker.image = "mongo"
    docker.link("mongo-container:mongo")
  end
end