- 将 JsonParserHelper 用作实用程序类。每次点击网址时。
a.) 上课并在该课程上分隔您的网址让假设 App_WebServiceUrls
public class App_WebServiceUrls {
public static String GetDetails ="http://dev.abctest.com/api/v1/book";
}
2.现在调用webservice/Web Api时。在单独的线程中进行 api 调用或使用 Asynctasks 来避免 NetworkOnMainThredException。
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
// Add your data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair(customer_firstname, "Deepak"));
nameValuePair.add(new BasicNameValuePair(customer_lastname, "Panwar"));
JSONObject json = null;
try {
json = new JSONObject();
json = JsonParserHelper.makeHttpRequest(
App_WebServiceUrls.CompanyDivisions, "GET", nameValuePair);
Log.d("Division List Response:", "" + json);
if (json != null) {
}else
{
/**To print tost on ui thread**/
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
/**Write Toast here**/
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}).start();
/用于进行 webapi 调用的辅助类/
public class JsonParserHelper {
static InputStream is = null;
static JSONObject jObj = null;
static JSONArray jArr = null;
static String json = "";
public static JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
try {
if (method == "POST") {
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
Log.v("Urltocheck", "" + url);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
Log.v("Urltocheck", "" + url);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
// jArr = new JSONArray(json);
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String (Array)
// return jArr;
return jObj;
}
}