pingdesktop.Model.HttpHandler.java Source code

Java tutorial

Introduction

Here is the source code for pingdesktop.Model.HttpHandler.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pingdesktop.Model;

import java.io.IOException;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import static pingdesktop.Sample.HTTPhandlerSample.httpClient;

/**
 *
 * @author akhyar
 */
public class HttpHandler {

    private static final String BaseUrl = ConfigData.base_url;

    public static String doGet(String page_url) throws IOException {

        /* create the HTTP client and GET request */
        HttpGet httpGet = new HttpGet(BaseUrl + page_url);

        /* execute request */
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();

        /* process response */
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            String responseText = EntityUtils.toString(httpEntity);
            return responseText;
        } else {
            return "Invalid HTTP response: " + httpResponse.getStatusLine().getStatusCode();
        }

    }

    public static String doPost(List<NameValuePair> nvps, String target_url) throws IOException {

        /* create the HTTP client and POST request */
        HttpPost httpPost = new HttpPost(BaseUrl + target_url);

        /* add some request parameters for a form request */
        //        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        //
        //        nvps.add(new BasicNameValuePair("username", "pangeranweb"));
        //        nvps.add(new BasicNameValuePair("password", "anisnuzulan"));
        nvps.add(new BasicNameValuePair("Content-Type", "application/x-www-form-urlencoded"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

        /* execute request */
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();

        /* process response */
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            String responseText = EntityUtils.toString(httpEntity);
            return responseText;
        } else {
            return "Invalid HTTP response: " + httpResponse.getStatusLine().getStatusCode();
        }

    }
}