我想将JSON数据解析为Web服务的字符串参数。
我的课程如下所述。
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
//URL url = new URL("http://192.168.1.44:8080/api/BeVoPOSAPI/checklogin?nodeid=2");
//Log.d("shankar: ", ip+":"+port+"/"+node);
//String url = "http://"+ip+":"+port+"/api/BeVoPOSAPI/checklogin?nodeid="+node+"&login=";
//String url = "http://"+ip+":"+port+"/api/BeVoPOSAPI/checklogin?nodeid="+node+"&login=";
//String url = "http://192.168.1.60:8081/api/BeVoPOSAPI/checklogin?nodeid=2&login=";
String url = "http://ipa.azurewebsites.net/pos/savecheck?nodeid=2&checkxml=";
try {
// Add your data
String checkxml = new String(params[0]);
;
url = url.concat(checkxml);
Log.d("password", checkxml);
//HttpPost httppost = new HttpPost(url);
//HttpParams httpParameters = new BasicHttpParams();
//HttpConnectionParams.setConnectionTimeout(httpParameters, 1000);
//HttpConnectionParams.setSoTimeout(httpParameters, 1000);
//HttpClient httpClient = new DefaultHttpClient(httpParameters);
//HttpContext localContext = new BasicHttpContext();
HttpPost httpget = new HttpPost(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 300;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 500;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
/*List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
Log.d("password", password_check);
nameValuePairs.add(new BasicNameValuePair("login", password_check));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));*/
// Execute HTTP Post Request
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
httpClient.setParams(httpParameters);
HttpResponse response = httpclient.execute(httpget);
Log.d("Status", response.toString());
int responseCode = response.getStatusLine().getStatusCode();
String str = Integer.toString(responseCode);
Log.d("Responce code", str);
switch (responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if (entity != null) {
String responseBody = EntityUtils.toString(entity);
Log.d("Responce", responseBody.toString());
String jsonString = responseBody.toString();
}
break;
}
} catch (SocketTimeoutException e) {
error = "SocketTimeoutException";
} catch (ConnectTimeoutException e) {
error = "connectionTimeoutException";
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
//Log.d("Error", e.toString());
error = "ClientProtocolException";
} catch (IOException e) {
// TODO Auto-generated catch block
//Log.d("Error", e.toString());
error = "IOException";
}
return null;
}
我从另一个方法中解析了checkxml字符串。
checkxml包含以下详细信息作为字符串。
{
"layoutid": 1,
"total": "2.95",
"checkdiscountpercentage": 0,
"gratuityid": "",
"status": 141,
"checkdiscountshiftlevelid": "",
"checktimeeventid": "",
"isprintonbill": "",
"userid": 1,
"gratuitypercentage": "",
"checkdiscountreason": "",
"ordertype": 210,
"noofcustomer": 1,
"generatedon": "",
"istaxexcemt": 0,
"checkdefinitiontype": "",
"tableid": 1,
"customerid": 0,
"ticket": "new",
"checkdiscountamount": "0",
"tablename": 100,
"checkdiscountistaxadjust": "1",
"checkdiscounttax": "0",
"products": [
{
"menuitemname": "2",
"menuitemid": 1,
"reason": "",
"discountpercentage": 0,
"seatid": 1,
"timeeventid": "",
"SaleDetailsMenuItem_ID": "2",
"istaxexcemt": "2",
"taxamount": "0.2100",
"discounttax": "0",
"definitiontype": "",
"modifiers": [
{}
],
"discountamount": "0",
"istaxinclude": "2",
"seatname": "",
"shiftlevelid": "2",
"discountshiftlevelid": "",
"discountreason": "",
"status": "2",
"coursingid": "",
"qty": 2,
"ordertype": "",
"taxpercent": "2",
"taxids": [
{
"taxpercent": "7",
"Amount": "0.21",
"taxid": "1"
}
],
"holdtime": 0,
"price": 2.95,
"discountistaxadjust": 1,
"price2": 3
}
]
}
它抛出illegal argument
和thread pool exception
。请让我知道如何将此数据解析为上述网址的参数。
答案 0 :(得分:1)
这是我写的一个可以帮助你的方法,
public JSONObject connectClient(){
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 20000);
httpClient= new DefaultHttpClient(params);
HttpResponse httpResponse;
InputStream inputStream=null;
try{
HttpPost httpPost=new HttpPost(__PUT_YOUR_URL_HERE__);
StringEntity se=new StringEntity(__PUT_YOUR_STRING_HERE__);
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
httpResponse = httpClient.execute(httpPost);
responseCode = httpResponse.getStatusLine().getStatusCode();
long responsesize = httpResponse.getEntity().getContentLength();
HttpEntity entity=httpResponse.getEntity();
try{
inputStream=entity.getContent();
}
catch(IllegalStateException ise){
ise.printStackTrace();
}
catch(IOException ioe){
ioe.printStackTrace();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
String s=sb.toString();
if(responseCode==200)
output= new JSONObject(s);
else{
output.put("STATUS", "FAIL");
output.put("ERRORCODE", responseCode);
output.put("DATA_SIZE", responsesize);
output.put("DATA_CONTENT", s);
}
}
catch(Exception e){
e.printStackTrace();
}
return output;
}
再次给出响应是JSONObject,如果需要,可以编辑它。
答案 1 :(得分:1)
称之为new GetData().execute(url);
private class GetData extends AsyncTask<String, Void, JSONObject> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(Calendar.this, "", "");
}
@Override
protected JSONObject doInBackground(String... params) {
String response;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
HttpResponse responce = httpclient.execute(httppost);
HttpEntity httpEntity = responce.getEntity();
response = EntityUtils.toString(httpEntity);
Log.d("response is", response);
return new JSONObject(response);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
progressDialog.dismiss();
if(result != null)
{
try
{
JSONObject jobj = result.getJSONObject("result");
String status = jobj.getString("status");
if(status.equals("true"))
{
JSONArray array = jobj.getJSONArray("data");
for(int x = 0; x < array.length(); x++)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", array.getJSONObject(x).getString("name"));
map.put("date", array.getJSONObject(x).getString("date"));
map.put("description", array.getJSONObject(x).getString("description"));
list.add(map);
}
CalendarAdapter adapter = new CalendarAdapter(Calendar.this, list);
list_of_calendar.setAdapter(adapter);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
Toast.makeText(Calendar.this, "Network Problem", Toast.LENGTH_LONG).show();
}
}
}
// Json就是这个
{
result: {
data: [
{
name: "KICK-OFF personal . 6-7 augusti",
date: "2014/08/06 ",
description: "6-7 augusti har pedagogerna grov planering inför höst terminen projekt. Skaparverkstan har öppet som vanligt med vikarier."
}
],
status: "true",
description: "Data found"
}
}