Skip to content
Advertisement

REST Server-Client Communication

I’m developing an Android app in Java and I need to add a REST Server-Client Communication feature to it. I assume that the following code should post data to a .php file and will be thankful if someone explains to me what does it do and how to use it properly:

public static String urlAddress = "http://gp.gpashev.com:93/testTels/service.php";

public static String getPostDataString(HashMap<String, String> params)
        throws Exception
{
    StringBuilder feedback = new StringBuilder();
    boolean first = true;
    for(Map.Entry<String, String> entry: params.entrySet()){
        if(first == true){
            first = false;
        }else{
            feedback.append("&");
        }
        feedback.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        feedback.append("=");
        feedback.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }
    return feedback.toString();
}

public static String postData(String methodName, String userName, String fileJSON)
        throws Exception
{
    String result = "";
    HashMap<String, String> params = new HashMap<>();
    params.put("methodName", methodName);
    params.put("userName", userName);
    params.put("fileJSON", fileJSON);

    URL url = new URL(urlAddress);
    HttpURLConnection client = (HttpURLConnection) url.openConnection();
    client.setRequestMethod("POST");
    client.setRequestProperty("multipart/form-data", urlAddress+";charset=UTF-8");
    client.setDoInput(true);
    client.setDoOutput(true);
    OutputStream os = client.getOutputStream();
    BufferedWriter bw = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8")
    );
    String a = getPostDataString(params);
    bw.write(a);
    bw.close();
    os.close();

    int ResponseCode = client.getResponseCode();

    if(ResponseCode == HttpURLConnection.HTTP_OK){
        BufferedReader br = new BufferedReader(
                new InputStreamReader(client.getInputStream())
        );
        String line = "";
        while((line = br.readLine())!= null){
            result+=line+"n";
        }
        br.close();
    }else{
        throw new Exception("HTTP ERROR Response code: " + ResponseCode);
    }
    return result;
}

Advertisement

Answer

My answer is in as comments in your code:

public static String urlAddress = "http://gp.gpashev.com:93/testTels/service.php";

// parse Map to urlencode string: key1=value&key2=value2
// URL special char will be escaped, f.e.: ' ' to '%20'
public static String getPostDataString(HashMap<String, String> params)
        throws Exception
{
    StringBuilder feedback = new StringBuilder();
    boolean first = true;
    for(Map.Entry<String, String> entry: params.entrySet()){
        if(first == true){
            first = false;
        }else{
            feedback.append("&");
        }
        feedback.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        feedback.append("=");
        feedback.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }
    return feedback.toString();
}

public static String postData(String methodName, String userName, String fileJSON)
        throws Exception
{
    String result = ""; // not nessessary define here

    // create and fill paramters
    HashMap<String, String> params = new HashMap<>();
    params.put("methodName", methodName);
    params.put("userName", userName);
    params.put("fileJSON", fileJSON);

    // next 2 lines: prepare Http connection to URL
    URL url = new URL(urlAddress);
    HttpURLConnection client = (HttpURLConnection) url.openConnection();
    // set HTTP method to POST
    client.setRequestMethod("POST");
    // add request header multipart/form-data, I am not sure, if it is nessessary in this case
    client.setRequestProperty("multipart/form-data", urlAddress+";charset=UTF-8");
    // set connection for using input stream (reading response), default is true, btw.
    client.setDoInput(true);
    // set connection for using output stream (writing request)
    client.setDoOutput(true);

    // next 8 lines write parameters defined early to connection as urlencoded string
    // using try-with-resources is better
    OutputStream os = client.getOutputStream();
    BufferedWriter bw = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8")
    );
    String a = getPostDataString(params);
    bw.write(a);
    bw.close();
    os.close();

    // make request and receive response code
    int ResponseCode = client.getResponseCode();
    if(ResponseCode == HttpURLConnection.HTTP_OK){
        // read response from input stream to result variable defined early
        // using try-with-resources is better
        BufferedReader br = new BufferedReader(
                new InputStreamReader(client.getInputStream())
        );
        String line = "";
        while((line = br.readLine())!= null){
            result+=line+"n";
        }
        br.close();
    }else{
        throw new Exception("HTTP ERROR Response code: " + ResponseCode);
    }
    return result;
}

I hope this is helpfull. In general: postData make HTTP Post request on given URL. The code use method parameters as request body. If request returns 200 code, method returns response body as text, otherwise throws IOException.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement