Skip to content

Instantly share code, notes, and snippets.

@volkanceylan
Created January 24, 2016 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save volkanceylan/1b124f58c1e2b4fc7c7c to your computer and use it in GitHub Desktop.
Save volkanceylan/1b124f58c1e2b4fc7c7c to your computer and use it in GitHub Desktop.
Login to Serenity services with android and call service
public class ServiceHandler {
public ServiceHandler() {
}
public static String POST(String url, List<String> params){
InputStream inputStream = null;
String result = "";p
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpPost httpPostLogin = new HttpPost(url);
String jsonLogin = "";
JSONObject jsonObjectLogin = new JSONObject();
jsonObjectLogin.put("Username", "xxx");
jsonObjectLogin.put("Password", "yyy*");
jsonLogin = jsonObjectLogin.toString();
StringEntity seLogin = new StringEntity(jsonLogin);
httpPostLogin.setEntity(seLogin);
httpPostLogin.setHeader("Accept", "application/json");
httpPostLogin.setHeader("Content-type", "application/json");
HttpResponse httpResponseLogin = httpclient.execute(httpPostLogin, localContext);
inputStream = httpResponseLogin.getEntity().getContent();
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Can't connect to service!";
HttpPost httpPost = new HttpPost(params.get(1));
String json = "";
JSONObject jsonObject = new JSONObject();
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpclient.execute(httpPost, localContext);
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Can't connect to service!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
@chiangim
Copy link

@volkanceylan From your example. it seem i need trigger two service call for each service consume. Any other alternative?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment