Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.IOException;
import java.io.InputStream;

import java.net.HttpURLConnection;
import java.net.URL;

import java.util.HashMap;
import java.util.Map;

public class Main {

    public static String customrequestget(String url, HashMap<String, String> map, String method) {

        if (null != map) {
            int i = 0;
            for (Map.Entry<String, String> entry : map.entrySet()) {

                if (i == 0) {
                    url = url + "?" + entry.getKey() + "=" + entry.getValue();
                } else {
                    url = url + "&" + entry.getKey() + "=" + entry.getValue();
                }

                i++;
            }
        }
        try {

            URL murl = new URL(url);
            System.out.print(url);
            HttpURLConnection conn = (HttpURLConnection) murl.openConnection();
            conn.setConnectTimeout(5 * 1000);
            conn.setRequestMethod(method);

            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");

            InputStream inStream = conn.getInputStream();
            String result = inputStream2String(inStream);
            conn.disconnect();
            return result;
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }

    public static String inputStream2String(InputStream in) throws IOException {
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1;) {
            out.append(new String(b, 0, n));
        }
        return out.toString();
    }
}