http Url Setting - Android Network

Android examples for Network:HTTP

Description

http Url Setting

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 httpUrlSetting(String path, String param) {
        HttpURLConnection httpConnection = null;
        try {//ww w . j av a 2 s.  c o m
            byte[] data = param.getBytes(encoding);
            URL url = new URL(path);
            httpConnection = (HttpURLConnection) url.openConnection();
            // Output to the connection. Default is    
            // false, set to true because post    
            // method must write something to the    
            // connection    
            httpConnection.setDoOutput(true);
            // Read from the connection. Default is true.    
            httpConnection.setDoInput(true);
            // Set the post method. Default is GET    
            httpConnection.setRequestMethod("POST");
            // 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
            httpConnection.setRequestProperty("action", "authentication");
            //method: get
            httpConnection.setRequestProperty("method", "get");
            //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