Example usage for java.io UnsupportedEncodingException toString

List of usage examples for java.io UnsupportedEncodingException toString

Introduction

In this page you can find the example usage for java.io UnsupportedEncodingException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:com.example.yudiandrean.socioblood.databases.JSONParser.java

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

    // Making HTTP request
    try {/*  w w w  .  j  a  v  a2  s.  co  m*/
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        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();
        Log.e("JSON", json);
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

From source file:com.rvl.android.getnzb.GetNZB.java

public void login() {
    // Login to www.nzbs.org and go to search-activity. 
    // The return values from nzbs.org are stored in the cookiestore for later use.

    new Thread() {
        public void run() {
            if (!LOGGEDIN) {
                Log.d(Tags.LOG, "- login()");
                SharedPreferences pref = getSharedPreferences(Tags.PREFS, 0);
                Log.d(Tags.LOG,//from ww  w .j  a  v a2s.com
                        "Using login name: '" + pref.getString("nzbsusername", "No value given.") + "'");
                HttpPost post = new HttpPost(Tags.NZBS_LOGINPAGE);

                List<NameValuePair> nvp = new ArrayList<NameValuePair>(2);
                nvp.add(new BasicNameValuePair("username", pref.getString("nzbsusername", "")));
                nvp.add(new BasicNameValuePair("password", pref.getString("nzbspassword", "")));
                nvp.add(new BasicNameValuePair("action", "dologin"));

                try {
                    post.setEntity(new UrlEncodedFormEntity(nvp));
                    HttpResponse response = httpclient.execute(post);
                    HttpEntity entity = response.getEntity();

                    if (entity != null)
                        entity.consumeContent();

                    List<Cookie> cookielist = httpclient.getCookieStore().getCookies();
                    // If we are logged in we got three cookies. A a php-sessionid, username and a id-hash.
                    if (cookielist.isEmpty()) {
                        Log.d(Tags.LOG, "No cookies, not logged in.");
                    } else {
                        Log.d(Tags.LOG, "Received " + cookielist.size() + " cookies: ");
                        for (int i = 0; i < cookielist.size(); i++) {
                            Log.d(Tags.LOG, "- " + cookielist.get(i).toString());
                        }
                        LOGGEDIN = true;
                    }

                } catch (UnsupportedEncodingException e) {
                    Log.d(Tags.LOG, "login(): UnsupportedEncodingException: " + e.getMessage());
                } catch (ClientProtocolException e) {
                    Log.d(Tags.LOG, "login(): ClientProtocolException: " + e.getMessage());
                } catch (IOException e) {
                    httpclient = new DefaultHttpClient();
                    Log.d(Tags.LOG, "login(): IO Exception: " + e.getMessage());
                    Log.d(Tags.LOG, "login(): " + e.toString());
                }
            }
            pd_handler.sendEmptyMessage(0);
        }
    }.start();
}

From source file:com.example.pyrkesa.shwc.JSONParser.java

public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {

    // Making HTTP request
    try {/*from  ww  w .j ava2 s.c  o m*/

        // check for request method
        if (method == "POST") {
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            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;
            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 {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

From source file:Conexion.JSONParser.java

public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
    // Making HTTP request
    try {/*from w  w w.  j  a  v a 2s. co  m*/
        // check for request method
        if (method == "POST") {
            // request method is POST
            // defaultHttpClient
            System.out.println("url es: " + url);

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            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;
            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();
        System.out.println(json);
    } catch (Exception e) {
        System.out.println("Error converting result " + e.toString());
    }
    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        System.out.println("Error parsing data " + e.toString());
    }
    // return JSON String
    return jObj;
}

From source file:edu.txstate.dmlab.clusteringwiki.sources.AbsSearcher.java

/**
 * Practical implementation of the search method
 *//*from w  w  w  . j a  va2  s .c o m*/
public ICWSearchResultCol search(String service, String query, int start, int count) {

    AbsSearchResultCol col = null;

    if (baseUrlPath == null || baseUrlPath.length() < 10) {
        if (col == null)
            col = new AbsSearchResultCol(null);
        col.addError("Error calling AbS Search Service: invalid baseUrlPath.");
        return col;
    }

    //query specifics
    if (start < 1)
        start = 1;
    if (count < 0)
        count = getNumResults();

    //build service query
    String url = null;
    try {
        url = buildRequestUrl(service, query, start, count);
    } catch (UnsupportedEncodingException e) {
        if (col == null)
            col = new AbsSearchResultCol(null);
        col.addError("Error calling AbS Search Service: invalid query string.");
        return col;
    }

    //execute query
    try {

        String doc = URLUtils.getWebPage(url);
        JSONObject res = new JSONObject(doc);

        col = new AbsSearchResultCol(res);
        col.setDataSourceInfo(key, label);
        col.setFirstPosition(start);

    } catch (JSONException e) {
        if (col == null)
            col = new AbsSearchResultCol(null);
        col.addError("Error calling AbS Search Service: " + e.toString());
        return col;
    } catch (MalformedURLException e) {
        if (col == null)
            col = new AbsSearchResultCol(null);
        col.addError("Error calling AbS Search Service: " + e.toString());
        return col;
    } catch (IOException e) {
        // Most likely a network exception of some sort.
        if (col == null)
            col = new AbsSearchResultCol(null);
        col.addError("Error calling AbS Search Service: " + e.toString());
        return col;
    }

    return col;
}

From source file:com.klinker.android.spotify.data.AccessToken.java

/**
 * Get a new auth token from spotify by making all of the proper requests
 * @param address the address to direct request to
 * @param token the token from the oauth process
 * @param clientId the client id used to show that Tunes is the accessing app
 * @param clientSecret the client secret used to show that Tunes is the accessing app
 * @param redirectUri where to redirect to once the token has been fetched
 * @param grantType type of request/*w  ww  .ja v a  2  s . c o m*/
 * @return a JSON object with all of the token information as specified by Spotify
 */
public JSONObject getToken(String address, String token, String clientId, String clientSecret,
        String redirectUri, String grantType) {
    try {
        httpClient = getHttpClient();
        httpPost = new HttpPost(address);
        params.add(new BasicNameValuePair("code", token));
        params.add(new BasicNameValuePair("client_id", clientId));
        params.add(new BasicNameValuePair("client_secret", clientSecret));
        params.add(new BasicNameValuePair("redirect_uri", redirectUri));
        params.add(new BasicNameValuePair("grant_type", grantType));
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        HttpResponse httpResponse = executeRequest(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        inputStream = httpEntity.getContent();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = getBufferedReader(getInputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        inputStream.close();
        json = sb.toString();
        Log.e("JSONStr", json);
    } catch (Exception e) {
        e.getMessage();
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    try {
        jsonObject = createJSON(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    return jsonObject;
}

From source file:org.ednovo.goorusearchwidget.JSONParser.java

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {/*from  w ww.j av a  2s.co  m*/
        // default implementation of HttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);//Executes a request using the default context...Returns
        //the response to the request. This is always a final response, never an intermediate response with an 1xx status code. Whether redirects or authentication challenges will be returned or handled automatically depends on the implementation and configuration of this client.

        HttpEntity httpEntity = httpResponse.getEntity();//Obtains the message entity of this response, if any...Returns
        //the response entity, or null if there is none 

        is = httpEntity.getContent(); //a new input stream that returns the entity data.

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));//BufferedReader - Constructs a new BufferedReader, providing in with a buffer of 8192 characters.

        //Parameters   InputStreamReader - input stream from which to read characters

        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 {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    System.out.println("arpit tyagi");
    return jObj;

}

From source file:com.scytulip.nrfUARTbackrec.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    Log.i(TAG, "onCreate");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*from   www .  ja v  a  2  s.  co  m*/
    mBtAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBtAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        finish();
        return;
    }
    messageListView = (ListView) findViewById(R.id.listMessage);
    listAdapter = new ArrayAdapter<String>(this, R.layout.message_detail);
    messageListView.setAdapter(listAdapter);
    messageListView.setDivider(null);
    btnConnectDisconnect = (Button) findViewById(R.id.btn_select);
    btnSend = (Button) findViewById(R.id.sendButton);
    btnDwnd = (Button) findViewById(R.id.dlButton);
    edtMessage = (EditText) findViewById(R.id.sendText);
    service_init();

    mBackData = new BackRecData(getApplicationContext());

    // Handler Disconnect & Connect button
    btnConnectDisconnect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mBtAdapter.isEnabled()) {
                Log.i(TAG, "onClick - BT not enabled yet");
                Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            } else {
                if (btnConnectDisconnect.getText().equals("Connect")) {

                    //Connect button pressed, open DeviceListActivity class, with popup windows that scan for devices

                    Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class);
                    startActivityForResult(newIntent, REQUEST_SELECT_DEVICE);
                } else {
                    //Disconnect button pressed
                    if (mDevice != null) {
                        mService.disconnect();

                    }
                }
            }
        }
    });
    // Handler Send button  
    btnSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText editText = (EditText) findViewById(R.id.sendText);
            String message = editText.getText().toString();
            byte[] value;
            try {
                //send data to service
                value = message.getBytes("UTF-8");
                mService.writeRXCharacteristic(value);
                //Update the log with time stamp
                String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
                listAdapter.add("[" + currentDateTimeString + "] TX: " + message);
                messageListView.smoothScrollToPosition(listAdapter.getCount() - 1);
                edtMessage.setText("");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });

    // Handler Download Button
    btnDwnd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                mService.writeRXCharacteristic("T".getBytes("UTF-8"));
            } catch (Exception e) {
                Log.i(TAG, e.toString());
            }

        }
    });

    // Set initial UI state

}

From source file:org.cerberus.crud.dao.impl.TestCaseCountryPropertiesDAO.java

@Override
public void deleteTestCaseCountryProperties(TestCaseCountryProperties tccp) throws CerberusException {
    boolean throwExcep = false;
    final String query = "DELETE FROM testcasecountryproperties WHERE test = ? and testcase = ? and country = ? and hex(`property`) like hex(?)";

    Connection connection = this.databaseSpring.connect();
    try {/*from  w w  w .  ja v  a 2  s  .c  o  m*/
        PreparedStatement preStat = connection.prepareStatement(query);
        try {
            preStat.setString(1, tccp.getTest());
            preStat.setString(2, tccp.getTestCase());
            preStat.setString(3, tccp.getCountry());
            preStat.setBytes(4, tccp.getProperty().getBytes("UTF-8"));

            throwExcep = preStat.executeUpdate() == 0;
        } catch (SQLException exception) {
            LOG.error("Unable to execute query : " + exception.toString());
        } catch (UnsupportedEncodingException ex) {
            LOG.error(ex.toString());
        } finally {
            preStat.close();
        }
    } catch (SQLException exception) {
        LOG.error("Unable to execute query : " + exception.toString());
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            LOG.warn(e.toString());
        }
    }
    if (throwExcep) {
        throw new CerberusException(new MessageGeneral(MessageGeneralEnum.CANNOT_UPDATE_TABLE));
    }
}