call Url - Java Network

Java examples for Network:URL Download

Description

call Url

Demo Code


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

import java.net.URL;
import java.net.URLConnection;

import java.net.URLEncoder;

import java.util.Map;

public class Main {
    public static String callUrl(String urlString,
            Map<String, String> paramMap) {
        String urlReturnValue = "";
        try {/*from   w w  w  .  j  a  va  2  s  .c o  m*/
            // Construct data
            StringBuffer dataBuf = new StringBuffer();
            boolean firstParam = true;
            for (String paramKey : paramMap.keySet()) {
                if (!firstParam)
                    dataBuf.append("&");
                dataBuf.append(URLEncoder.encode(paramKey, "UTF-8"))
                        .append("=")
                        .append(URLEncoder.encode(paramMap.get(paramKey),
                                "UTF-8"));
                firstParam = false;
            }
            String data = dataBuf.toString();

            // Send data
            URL url = new URL(urlString);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(
                    conn.getOutputStream());
            wr.write(data);
            wr.flush();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                urlReturnValue = urlReturnValue + line;
            }
            wr.close();
            rd.close();
        } catch (Exception e) {
            e.printStackTrace();
            urlReturnValue = "";
        }
        return urlReturnValue;

    }
}

Related Tutorials