简体   繁体   English

如何在Java,Android上对我的Web服务进行POST查询?

[英]How can I make POST query for my web-service on Java, Android?

I have code for POST query on Java 我在Java上有用于POST查询的代码

    ArrayList<HashMap<String, String>> books=SQLiteDbWrapper.getInstance().getAllBooks();
    JSONObject object=new JSONObject();
    object.put("key", KEY);

    JSONArray isbns=new JSONArray();
    for (HashMap<String, String> book:books) {
        isbns.put(book.get(SQLiteDbHelper.ISBN13_FIELD));
    }

    object.put("isbns", isbns);
    object.put("email", email);
    Log.e("log", object.toString());
    HttpClient client = new DefaultHttpClient();
    HttpPost request = new HttpPost(BASE_URL+SUBMIT_SCRIPT);

    request.setEntity(new ByteArrayEntity(
        object.toString().getBytes("UTF8")));
    HttpResponse response = client.execute(request);

I need to send JSON data into server; 我需要将JSON数据发送到服务器; my web-service must get this data from $POST['json'] variable, but I don't know how can I put my JSONObject object into 'json' field for POST query? 我的Web服务必须从$ POST ['json']变量中获取此数据,但是我不知道如何将JSONObject对象放入POST查询的'json'字段中? Please, help me 请帮我

You must do as follows: 您必须执行以下操作:

String jsonValue = object.toString();
String encoded = java.net.URLEncoder.encode(jsonValue, "UTF-8");

List<NameValuePair> formData = new ArrayList<NameValuePair>();
formData.add(new NameValuePair("json", encoded));

request.setHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestBody(formData);

response = client.execute(request);

Your code looks OK. 您的代码看起来不错。 All I see is a missing content type in the HttpPost object. 我所看到的只是HttpPost对象中缺少的内容类型。

request.setHeader("Content-Type", "application/json");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM