Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/**
 * Eliademy
 *
 * @copyright CBTec Oy
 * @license   All rights reserved
 */

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import org.json.JSONObject;

import android.util.Log;

public class Main {
    public static String initializeService(String data, String serviceName, String serviceUrl) {
        Log.d("EliademyUtils", "initializeService");
        try {
            JSONObject jsObj = new JSONObject(data.toString());
            DefaultHttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost(serviceUrl + "/login/token.php");

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("username", jsObj.get("username").toString()));
            nameValuePairs.add(new BasicNameValuePair("password", jsObj.get("password").toString()));
            nameValuePairs.add(new BasicNameValuePair("service", serviceName));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse response = httpclient.execute(httppost);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                StringBuilder jsonStr = new StringBuilder();
                InputStream iStream = entity.getContent();
                BufferedReader bufferReader = new BufferedReader(new InputStreamReader(iStream));
                String jpart;
                while ((jpart = bufferReader.readLine()) != null) {
                    jsonStr.append(jpart);
                }
                iStream.close();
                Log.d("Moodle", jsonStr.toString());
                JSONObject jsonObj = new JSONObject(jsonStr.toString());
                return (String) jsonObj.get("token");
            }
        } catch (Exception e) {
            Log.e("EliademyUtils", "exception", e);
            return null;
        }
        return null;
    }
}