http Url Set - Android Network

Android examples for Network:HTTP

Description

http Url Set

Demo Code


//package com.java2s;

import java.io.IOException;

import java.io.OutputStream;
import java.net.HttpURLConnection;

import java.net.URL;

public class Main {
    static String encoding = "UTF-8";

    public static HttpURLConnection httpUrlSet(String path, String param,
            String method, String action) {
        HttpURLConnection httpConnection = null;
        try {/*from   w  w  w .  j a va  2 s .c om*/
            byte[] data = param.getBytes(encoding);
            URL url = new URL(path);
            httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection.setDoOutput(true);
            // Read from the connection. Default is true.    
            httpConnection.setDoInput(true);
            // Set the post method. Default is GET    
            httpConnection.setRequestMethod("GET");
            // Post cannot use caches    
            //Content-Type: application/json; charset=utf-8//application/x-www-form-urlencoded
            httpConnection.setUseCaches(false);
            httpConnection.setInstanceFollowRedirects(true);
            //Content-Type: application/x-www-form-urlencoded
            httpConnection.setRequestProperty("Content-Type",
                    "application/x-javascript; charset=" + encoding);

            //         httpConnection.setRequestProperty("Content-Type",    
            //               "application/x-www-form-urlencoded"); 
            //         httpConnection.setRequestProperty("Content-Length",    
            //               String.valueOf(data.length));
            httpConnection.setRequestProperty("appKey", "kxzcsc");
            //action: authentication
            if (action.equals("NOACTION")) {

            } else if (!action.equals("")) {
                httpConnection.setRequestProperty("action", action);
            } else {
                httpConnection.setRequestProperty("action",
                        "authentication");
            }

            if (!method.equals("")) {
                httpConnection.setRequestProperty("method", method);
            }

            //If-Modified-Since: Sat, 23 Aug 2014 19:26:12 GMT
            //httpConnection.addRequestProperty("If-Modified-Since", "Sat, 23 Aug 2014 19:26:12 GMT");
            httpConnection.connect();
            OutputStream outStream = httpConnection.getOutputStream();
            outStream.write(data);
            outStream.flush();
            outStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return httpConnection;

    }
}

Related Tutorials