我需要从android调用一个带有服务器认证的webservice(HTTPS)。请帮我怎么做。
如果我在浏览器中尝试URL,则要求输入用户名和密码。如何在使用HTTPS webservice进行验证时提供用户名和密码?
感谢。
答案 0 :(得分:0)
你可以使用asytask类来调用webservices,在Asyntask类中我们基本上有四种方法 1.onPreexcute:用于显示数据正在加载。 2.doInBackground:用于向服务器发送数据和从服务器加载数据。 3.onPostExcute:用于从服务器加载数据后,这里基本上是UI实现的任务必须完成。
class MyAsyntask extends AsyncTask<String, Void, String> {
String responseString;
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progress = new ProgressDialog(getActivity());
progress.setMessage("Please wait Data is loading...");
progress.show();
}
@Override
protected String doInBackground(String... params) {
String json = null;
String url = "your url";
try {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
5);
nameValuePairs.add(new BasicNameValuePair("UserNAme",
yourusername));
nameValuePairs.add(new BasicNameValuePair("Password",
yourpassword);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Encoding POST data
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
responseString = EntityUtils.toString(entity);
Log.d("Mychat reasponse", responseString);
System.out.println(responseString);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return url;
}
@Override
protected void onPostExecute(String string) {
// TODO Auto-generated method stub
super.onPostExecute(string);
if (progress.isShowing()) {
progress.dismiss();
}
}
你可以用Json格式从服务器获得响应,根据json结构,你可以解析json。