get Result from url - Java Network

Java examples for Network:URL

Description

get Result from url

Demo Code


import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main{

    //from ww  w .  j  a  v  a2 s .c om
    private static String getResult(String urlStr, String content,
            String encoding) {
        URL url = null;
        HttpURLConnection connection = null;
        try {
            url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();// 
            connection.setConnectTimeout(2000);// 
            connection.setReadTimeout(2000);// 
            connection.setDoOutput(true);//  true|false
            connection.setDoInput(true);// true|false
            connection.setRequestMethod("POST");// POST|GET
            connection.setUseCaches(false);// true|false
            connection.connect();// 
            DataOutputStream out = new DataOutputStream(
                    connection.getOutputStream());// 
            out.writeBytes(content);// ?,? name=xxx&pwd=xxx
            out.flush();// 
            out.close();// 
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(),
                            encoding));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            reader.close();
            return buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();// 
            }
        }
        return null;
    }
}

Related Tutorials