我有web服务,我想创建一个类,应该在哈希表认证后从服务器获取电子邮件和密码,然后在共享首选项中保存电子邮件和密码。
尝试这个类在你的应用程序中调用webservice,我分享get和post两种方法,你可以根据你的需要使用任何一个。
public class CallService {
String url;
HttpEntity str1;
String str;
Context context;
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public CallService(String url1) {
this.url = url1;
}
public String getResponceWithPost() {
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,5000000);
HttpConnectionParams.setSoTimeout(httpParameters,500000);
HttpConnectionParams.setTcpNoDelay(httpParameters,true);
HttpClient hc = new DefaultHttpClient(httpParameters);
HttpPost post= new HttpPost (url);
HttpResponse rp = hc.execute(post);
// //////////////
if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
str = EntityUtils.toString(rp.getEntity());
Log.e("Calling service", str);
return str;
}
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int getResponceWithGet() {
int code = 0;
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse rp = hc.execute(get);
code= rp.getStatusLine().getStatusCode();
return code;
} catch (IOException e) {
Log.e("calling service", e.toString());
e.printStackTrace();
}
catch(Exception e)
{
Log.e("calling service", e.toString());
}
return code;
}}
这将返回服务器的响应,如电子邮件密码或其他详细信息。你可以将这些细节保存在sharedpreference中。对于共享首选项,请遵循-
http://developer.android.com/guide/topics/data/data-storage.html参照
和在你的活动调用你的url使用我的调用服务类,像这样-
在activity中像这样声明hashTable
Hashtable hashtable = new Hashtable();
调用这个方法
new checkForLogin().execute();
和你的异步类
class checkForLogin extends AsyncTask<Void, Void,String>
{
@Override
protected void onPreExecute() {
progress= ProgressDialog.show(LoginScreen.this,"Authenticating !","Please Wait");
}
@Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
Parse your json data here that will be in data
CallService cl2=new CallService("your server url here");
Log.e("login url is",""+Urls.loginurl);
data=cl2.getResponceWithPost();
Log.e("server response data","data = "+data);
hashtable.put(“email″, data.getString("email"));
hashtable.put(“pass″, data.getString("pass"));
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progress.dismiss();
}