【发布时间】:2015-02-03 06:14:01
【问题描述】:
以下是我的代码。它返回空数组,例如:Array ( ) 请检查下面的代码,让我知道要进行哪些更改。我正在创建一个 JSON 数组并希望将其发布到一个 url。
String checkin = edit_message.getText().toString();
HttpClient httpclient = new DefaultHttpClient();
String httppostURL = "http:// ...";
HttpPost httppost = new HttpPost(httppostURL);
Log.v(TAG, "postURL: " + httppost);
JSONObject data1 = new JSONObject();
data1.put("merchant_id", "02");
data1.put("merchant_location_id", "03");
data1.put("user_id", "04");
data1.put("merchant_kiosk_id", "04");
data1.put("subscriber_phone", checkin);
JSONArray jsonArray = new JSONArray();
jsonArray.put(data1);
JSONObject data= new JSONObject();
data.put("data",jsonArray);
httppost.setHeader(HTTP.CONTENT_TYPE,"application/x-www-form-urlencoded;charset=UTF-8");
//httppost.setEntity(new UrlEncodedFormEntity(data , "UTF-8"));
StringEntity se= new StringEntity(data.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v(TAG, "Response: " + responseStr);
Log.i("TAG",""+response.getStatusLine().getStatusCode());
Toast.makeText(CheckinActivity.this, responseStr, Toast.LENGTH_LONG).show();
//you can add an if statement here and do other actions based on the response
}
edit_message.setText("");
//Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show();
Toast.makeText(CheckinActivity.this, "Data: " +data,Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Throwable t) {
Toast.makeText(CheckinActivity.this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
}
更新:
代替
JSONObject data= new JSONObject();
data.put("data",jsonArray);
我用过:
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("data", data1.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
更新 2
我有一个这样的 json 响应
{"msg":Successfully logged in,"status":1}
如果状态 = 1,我想做一些活动;如果状态 = 0,我想做其他事情。如何做到这一点?以及将代码放在哪里?提前致谢。
【问题讨论】:
-
如果得到
Array ( )作为响应意味着问题出在服务器端的api中 -
列表
nvps = new ArrayList (); nvps.add(new BasicNameValuePair("data", data.toString())); httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); -
我有一个像这样的 json 响应 {"msg":Successfully logged in,"status":1} 如果状态 = 1,我想做一些活动,如果状态 = 0,我想做做点别的。如何做到这一点?以及将代码放在哪里?提前致谢。
标签: android arrays json parsing post