[英]How can I make POST query for my web-service on Java, Android?
我在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);
我需要將JSON數據發送到服務器; 我的Web服務必須從$ POST ['json']變量中獲取此數據,但是我不知道如何將JSONObject對象放入POST查詢的'json'字段中? 請幫我
您必須執行以下操作:
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);
您的代碼看起來不錯。 我所看到的只是HttpPost
對象中缺少的內容類型。
request.setHeader("Content-Type", "application/json");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.