集册 Java实例教程 从url获取结果

从url获取结果

欢马劈雪     最近更新时间:2020-01-02 10:19:05

510
从网址获取结果
/*来自 时 代 J a v a 公 众 号 - nowjava.com*/

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{


    /** 时代Java公众号 - N o w J a  v a . c o m 提供 **/

    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);

  
展开阅读全文