Example usage for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler

List of usage examples for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler

Introduction

In this page you can find the example usage for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler.

Prototype

BasicResponseHandler

Source Link

Usage

From source file:MainFrame.HttpCommunicator.java

public void setCombos(JComboBox comboGroups, JComboBox comboDates, LessonTableModel tableModel)
        throws MalformedURLException, IOException {
    BufferedReader in = null;/*from  w ww  . j a v  a  2 s  .c o  m*/
    if (SingleDataHolder.getInstance().isProxyActivated) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword));

        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
                .build();

        HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress,
                SingleDataHolder.getInstance().proxyPort);

        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");
        post.setConfig(config);

        StringBody head = new StringBody(new JSONObject().toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apideskviewer.getAllLessons", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);

        InputStream stream = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8));

        in = new BufferedReader(new InputStreamReader(stream));
    } else {
        URL obj = new URL(SingleDataHolder.getInstance().hostAdress);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "apideskviewer.getAllLessons={}";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + SingleDataHolder.getInstance().hostAdress);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    }

    JSONParser parser = new JSONParser();
    try {
        Object parsedResponse = parser.parse(in);

        JSONObject jsonParsedResponse = (JSONObject) parsedResponse;

        for (int i = 0; i < jsonParsedResponse.size(); i++) {
            String s = (String) jsonParsedResponse.get(String.valueOf(i));
            String[] splittedPath = s.split("/");
            DateFormat DF = new SimpleDateFormat("yyyyMMdd");
            Date d = DF.parse(splittedPath[1].replaceAll(".bin", ""));
            Lesson lesson = new Lesson(splittedPath[0], d, false);
            String group = splittedPath[0];
            String date = new SimpleDateFormat("dd.MM.yyyy").format(d);

            if (((DefaultComboBoxModel) comboGroups.getModel()).getIndexOf(group) == -1) {
                comboGroups.addItem(group);
            }
            if (((DefaultComboBoxModel) comboDates.getModel()).getIndexOf(date) == -1) {
                comboDates.addItem(date);
            }
            tableModel.addLesson(lesson);
        }
    } catch (Exception ex) {
    }
}

From source file:com.nagazuka.mobile.android.goedkooptanken.service.impl.GoogleHttpGeocodingService.java

public String download(String url) throws NetworkException {
    String response = "";
    try {//from   w  ww.j  a v  a2  s .  com
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        //Log.d(TAG, "<< HTTP Request: " + request.toString());

        ResponseHandler<String> handler = new BasicResponseHandler();
        response = httpClient.execute(request, handler);
        //Log.d(TAG, "<< HTTP Response: " + response);

        httpClient.getConnectionManager().shutdown();
    } catch (ClientProtocolException c) {
        c.printStackTrace();
        throw new NetworkException("Er zijn netwerkproblemen opgetreden bij het opvragen van de postcode", c);
    } catch (IOException e) {
        e.printStackTrace();
        throw new NetworkException("Er zijn netwerkproblemen opgetreden bij het opvragen van de postcode", e);
    }

    return response;
}

From source file:org.wso2.appserver.integration.tests.webapp.spring.SpringScopeTestCase.java

@Test(groups = "wso2.as", description = "Verfiy Spring Request scope")
public void testSpringRequestScope() throws Exception {

    String endpoint = webAppURL + "/" + webAppMode.getWebAppName() + "/scope/request";
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

    HttpGet httpget = new HttpGet(endpoint);
    HttpResponse response1 = httpClient.execute(httpget, httpContext);
    String responseMsg1 = new BasicResponseHandler().handleResponse(response1);
    HttpResponse response2 = httpClient.execute(httpget, httpContext);
    String responseMsg2 = new BasicResponseHandler().handleResponse(response2);
    httpClient.close();//from   w w w .  ja  v  a2 s . c om

    assertTrue(!responseMsg1.equalsIgnoreCase(responseMsg2), "Failed: Responses should not be the same");
}

From source file:com.attentec.ServerContact.java

/**
 * Posts POST request to url with data that from values.
 * Values are put together to a json object before they are sent to server.
 * postname = { subvar_1_name => subvar_1_value,
 *             subvar_2_name => subvar_2_value
 *             ...}/*from  www  .j a v  a2s  .  c  o  m*/
 * postname_2 = {...}
 * ...
 * @param values hashtable with structure:
 * @param url path on the server to call
 * @param ctx calling context
 * @return JSONObject with data from rails server.
 * @throws Login.LoginException when login is wrong
 */
public static JSONObject postJSON(final Hashtable<String, List<NameValuePair>> values, final String url,
        final Context ctx) throws Login.LoginException {
    //fetch the urlbase
    urlbase = PreferencesHelper.getServerUrlbase(ctx);

    //create a JSONObject of the hashtable
    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    Enumeration<String> postnames = values.keys();

    String postname;
    List<NameValuePair> postvalues;
    JSONObject postdata;

    while (postnames.hasMoreElements()) {
        postname = (String) postnames.nextElement();
        postvalues = values.get(postname);
        postdata = new JSONObject();
        for (int i = 0; i < postvalues.size(); i++) {
            try {
                postdata.put(postvalues.get(i).getName(), postvalues.get(i).getValue());
            } catch (JSONException e) {
                Log.w(TAG, "JSON fail");
                return null;
            }
        }
        pairs.add(new BasicNameValuePair(postname, postdata.toString()));
    }

    //prepare the http call
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, CONNECTION_TIMEOUT);

    HttpClient client = new DefaultHttpClient(httpParams);

    HttpPost post = new HttpPost(urlbase + url);
    //Log.d(TAG, "contacting url: " + post.getURI());
    try {
        post.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        return null;
    }

    //call the server
    String response = null;
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    try {
        response = client.execute(post, responseHandler);
    } catch (IOException e) {
        Log.e(TAG, "Failed in HTTP request: " + e.toString());
        return null;
    }
    //Log.d(TAG, "Have contacted url success: " + post.getURI());
    //read response
    JSONObject jsonresponse;
    try {

        jsonresponse = new JSONObject(response);
    } catch (JSONException e) {
        Log.e(TAG, "Incorrect response from server" + e.toString());
        return null;
    }
    String responsestatus;
    try {
        responsestatus = jsonresponse.getString("Responsestatus");
    } catch (JSONException e1) {
        return null;
    }
    if (!responsestatus.equals("Wrong login")) {
        return jsonresponse;
    } else {
        Log.w(TAG, "Wrong login");
        throw new Login.LoginException("Wrong login");
    }
}

From source file:net.networksaremadeofstring.cyllell.Cuts.java

public Cuts(Context thisContext) throws Exception {
    settings = thisContext.getSharedPreferences("Cyllell", 0);

    responseHandler = new BasicResponseHandler();

    if (settings.getString("URL", "--").equals("--") == false
            && settings.getString("ClientName", "--").equals("--") == false
            && settings.getString("PrivateKey", "--").equals("--") == false) {
        ChefAuth = new Authentication(settings.getString("ClientName", "--"),
                settings.getString("PrivateKey", "--"));
        this.ChefURL = settings.getString("URL", "--");
        this.PathSuffix = settings.getString("Suffix", "");
    } else {//w ww .ja  v a2 s  .c om
        //Log.i("URL",settings.getString("URL", "--"));
        //Log.i("ClientName",settings.getString("ClientName", "--"));
        //Log.i("PrivateKey",settings.getString("PrivateKey", "--"));
        throw new Exception("Chef URL is not set");
    }

    //Create the httpclient that trusts everything!
    this.PrepareSSLHTTPClient();
}

From source file:com.zextras.zimbradrive.UploadFileHttpHandler.java

private String createResponseForZimlet(HttpResponse fileRequestResponseFromDrive) {
    BasicResponseHandler basicResponseHandler = new BasicResponseHandler();
    String responseBody;/*ww  w. j av  a2  s  . com*/
    try {
        responseBody = basicResponseHandler.handleResponse(fileRequestResponseFromDrive);
    } catch (IOException e) {
        ZimbraLog.extensions.debug("Unable to create response for zimlet", e);
        throw new RuntimeException();
    }

    JSONObject jsonResponse = new JSONObject(responseBody);

    int responseCode = fileRequestResponseFromDrive.getStatusLine().getStatusCode();

    return htmlResponse(jsonResponse.toString(), responseCode);
}

From source file:sample.jdbc.StagemonitorIntegrationTest.java

@Test
public void testStagemonitorSqlQueriesAreCollected() throws Exception {
    final String requestTrace = getRequestTrace(
            httpClient.execute(new HttpGet("http://localhost:" + this.port), new BasicResponseHandler()));
    assertTrue(requestTrace.contains("IndexController.index"));
    assertTrue(requestTrace.contains("SELECT * FROM Note"));
}

From source file:hotandcold.HNCAPI.java

public boolean setCoord(int id, coord c) {

    String request = servIP + "verb=p&id=" + id;

    request += "&long=" + c.lon + "&lat=" + c.lat;

    HttpClient client = new DefaultHttpClient();

    HttpGet get = new HttpGet(request);

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    try {//from  w w  w .j a  v a  2 s . c  om
        client.execute(get, responseHandler);

        return true;
    } catch (IOException ex) {
        Logger.getLogger(HNCAPI.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
}

From source file:com.moods_final.moods.entertainment.YouTubeAPIDemoActivity.java

public ArrayList<String> getTopics() throws IOException {
    String searchUrl = "http://moods.esy.es/youtube.php";
    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(searchUrl);

    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    String responseBody = null;//from  www . j ava 2  s . co  m

    responseBody = client.execute(get, responseHandler);

    Log.e("aaa", responseBody);

    String id = "";
    String title = "";

    Log.e("aaa", "in showJson()");
    try {
        JSONObject jsonObject = new JSONObject(responseBody);
        JSONArray result = jsonObject.getJSONArray("result");

        for (int i = 0; i < result.length(); i++) {
            JSONObject Data = result.getJSONObject(i);

            id = Data.getString("id");
            title = Data.getString("title");
            //                topics.add(new String());

            topid.add("" + id);
            topics.add("" + title);
            Log.e("aaa", id + "  --- " + title);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return topics;
}