send Get URL and set user-agent - Android Network

Android examples for Network:URL

Description

send Get URL and set user-agent

Demo Code


//package com.java2s;
import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

public class Main {

    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {//  www  .  j a v  a2s.  c o m
            String urlName = url + "" + param;
            URL realUrl = new URL(urlName);
            // URL
            URLConnection conn = realUrl.openConnection();
            // 
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            // 
            conn.connect();
            // 
            Map<String, List<String>> map = conn.getHeaderFields();
            // 
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // BufferedReaderURL
            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("GET" + e);
            e.printStackTrace();
        }
        // finally
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
}

Related Tutorials