java实现url访问(get,post)

1.第一种方式

public class HttpUtils {  

    public static void main(String[] args) {  
        System.out.println(SMS("", "https://www.baidu.com/"));  
    }  

    private static String SMS(String postData, String postUrl) {  
        try {  
            // 发送POST请求  
            URL url = new URL(postUrl);  
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
            conn.setRequestMethod("POST");//修改发送方式  
            conn.setRequestProperty("Content-Type",  
                    "application/x-www-form-urlencoded");  
            conn.setRequestProperty("Connection", "Keep-Alive");  
            conn.setUseCaches(false);  
            conn.setDoOutput(true);  

            conn.setRequestProperty("Content-Length", "" + postData.length());  
            OutputStreamWriter out = new OutputStreamWriter(  
                    conn.getOutputStream(), "UTF-8");  
            out.write(postData);  
            out.flush();  
            out.close();  

            // 获取响应状态  
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {  
                return "";  
            }  
            // 获取响应内容体  
            String line, result = "";  
            BufferedReader in = new BufferedReader(new InputStreamReader(  
                    conn.getInputStream(), "utf-8"));  
            while ((line = in.readLine()) != null) {  
                result += line + "\n";  
            }  
            in.close();  
            return result;  
        } catch (IOException e) {  
        }  
        return "";  
    }  
}  

2.第二种方式

import java.io.ByteArrayOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.io.UnsupportedEncodingException;  
import java.net.HttpURLConnection;  
import java.net.MalformedURLException;  
import java.net.ProtocolException;  
import java.net.URL;  
import java.net.URLEncoder;  
import java.util.Iterator;  
import java.util.Map;  
import java.util.Map.Entry;  

public class HttpUtils {  

    private static final int TIME_OUT = 5;  
    /** 
     * 通过HTTP GET 发送参数 
     *  
     * @param httpUrl 
     * @param parameter 
     * @param httpMethod 
     */  
    public static String sendGet(String httpUrl, Map<String, String> parameter) {  
        if (parameter == null || httpUrl == null) {  
            return null;  
        }  

        StringBuilder sb = new StringBuilder();  
        Iterator<Map.Entry<String, String>> iterator = parameter.entrySet().iterator();  
        while (iterator.hasNext()) {  
            if (sb.length() > 0) {  
                sb.append('&');  
            }  
            Entry<String, String> entry = iterator.next();  
            String key = entry.getKey();  
            String value;  
            try {  
                value = URLEncoder.encode(entry.getValue(), "UTF-8");  
            } catch (UnsupportedEncodingException e) {  
                value = "";  
            }  
            sb.append(key).append('=').append(value);  
        }  
        String urlStr = null;  
        if (httpUrl.lastIndexOf('?') != -1) {  
            urlStr = httpUrl + '&' + sb.toString();  
        } else {  
            urlStr = httpUrl + '?' + sb.toString();  
        }  

        HttpURLConnection httpCon = null;  
        String responseBody = null;  
        try {  
            URL url = new URL(urlStr);  
            httpCon = (HttpURLConnection) url.openConnection();  
            httpCon.setDoOutput(true);  
            httpCon.setRequestMethod("GET");  
            httpCon.setConnectTimeout(TIME_OUT * 1000);  
            httpCon.setReadTimeout(TIME_OUT * 1000);  
            // 开始读取返回的内容  
            InputStream in = httpCon.getInputStream();  
            byte[] readByte = new byte[1024];  
            // 读取返回的内容  
            int readCount = in.read(readByte, 0, 1024);  
            ByteArrayOutputStream baos = new ByteArrayOutputStream();  
            while (readCount != -1) {  
                baos.write(readByte, 0, readCount);  
                readCount = in.read(readByte, 0, 1024);  
            }  
            responseBody = new String(baos.toByteArray(), "UTF-8");  
            baos.close();  
        } catch (Exception e) {  
        } finally {  
            if (httpCon != null)  
                httpCon.disconnect();  
        }  
        return responseBody;  
    }  

    /** 
     * 使用HTTP POST 发送文本 
     *  
     * @param httpUrl 
     *            发送的地址 
     * @param postBody 
     *            发送的内容 
     * @return 返回HTTP SERVER的处理结果,如果返回null,发送失败 
     */  
    public static String sentPost(String httpUrl, String postBody) {  
        return sentPost(httpUrl, postBody, "UTF-8", null);  
    }  

    /** 
     * 使用HTTP POST 发送文本 
     *  
     * @param httpUrl 
     *            发送的地址 
     * @param postBody 
     *            发送的内容 
     * @return 返回HTTP SERVER的处理结果,如果返回null,发送失败 
     */  
    public static String sentPost(String httpUrl, String postBody, String encoding) {  
        return sentPost(httpUrl, postBody, encoding, null);  
    }  

    /** 
     * 使用HTTP POST 发送文本 
     * @param httpUrl   目的地址 
     * @param postBody  post的包体 
     * @param headerMap 增加的Http头信息 
     * @return 
     */  
    public static String sentPost(String httpUrl, String postBody, Map<String, String> headerMap) {  
        return sentPost(httpUrl, postBody, "UTF-8", headerMap);  
    }  

    /** 
     * 使用HTTP POST 发送文本 
     *  
     * @param httpUrl 
     *            发送的地址 
     * @param postBody 
     *            发送的内容 
     * @param encoding 
     *            发送的内容的编码 
     * @param headerMap 增加的Http头信息           
     * @return 返回HTTP SERVER的处理结果,如果返回null,发送失败 
     * ................. 
     */  
    public static String sentPost(String httpUrl, String postBody, String encoding, Map<String, String> headerMap) {  
        HttpURLConnection httpCon = null;  
        String responseBody = null;  
        URL url = null;  
        try {  
            url = new URL(httpUrl);  
        } catch (MalformedURLException e1) {  
            return null;  
        }  
        try {  
            httpCon = (HttpURLConnection) url.openConnection();  
        } catch (IOException e1) {  
            return null;  
        }  
        if (httpCon == null) {  
            return null;  
        }  
        httpCon.setDoOutput(true);  
        httpCon.setConnectTimeout(TIME_OUT * 1000);  
        httpCon.setReadTimeout(TIME_OUT * 1000);  
        httpCon.setDoOutput(true);  
        httpCon.setUseCaches(false);  
        try {  
            httpCon.setRequestMethod("POST");  
        } catch (ProtocolException e1) {  
            return null;  
        }  
        if (headerMap != null) {  
            Iterator<Entry<String, String>> iterator = headerMap.entrySet().iterator();  
            while (iterator.hasNext()) {  
                Entry<String, String> entry = iterator.next();  
                httpCon.addRequestProperty(entry.getKey(), entry.getValue());  
            }  
        }  
        OutputStream output;  
        try {  
            output = httpCon.getOutputStream();  
        } catch (IOException e1) {  
            return null;  
        }  
        try {  
            output.write(postBody.getBytes(encoding));  
        } catch (UnsupportedEncodingException e1) {  
            return null;  
        } catch (IOException e1) {  
            return null;  
        }  
        try {  
            output.flush();  
            output.close();  
        } catch (IOException e1) {  
            return null;  
        }  
        // 开始读取返回的内容  
        InputStream in;  
        try {  
            in = httpCon.getInputStream();  
        } catch (IOException e1) {  
            return null;  
        }  
        /** 
         * 这个方法可以在读写操作前先得知数据流里有多少个字节可以读取。 
         * 需要注意的是,如果这个方法用在从本地文件读取数据时,一般不会遇到问题, 
         * 但如果是用于网络操作,就经常会遇到一些麻烦。 
         * 比如,Socket通讯时,对方明明发来了1000个字节,但是自己的程序调用available()方法却只得到900,或者100,甚至是0, 
         * 感觉有点莫名其妙,怎么也找不到原因。 
         * 其实,这是因为网络通讯往往是间断性的,一串字节往往分几批进行发送。 
         * 本地程序调用available()方法有时得到0,这可能是对方还没有响应,也可能是对方已经响应了,但是数据还没有送达本地。 
         * 对方发送了1000个字节给你,也许分成3批到达,这你就要调用3次available()方法才能将数据总数全部得到。 
         *  
         * 经常出现size为0的情况,导致下面readCount为0使之死循环(while (readCount != -1) {xxxx}),出现死机问题 
         */  
        int size = 0;  
        try {  
            size = in.available();  
        } catch (IOException e1) {  
            return null;  
        }  
        if (size == 0) {  
            size = 1024;  
        }  
        byte[] readByte = new byte[size];  
        // 读取返回的内容  
        int readCount = -1;  
        try {  
            readCount = in.read(readByte, 0, size);  
        } catch (IOException e1) {  
            return null;  
        }  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        while (readCount != -1) {  
            baos.write(readByte, 0, readCount);  
            try {  
                readCount = in.read(readByte, 0, size);  
            } catch (IOException e) {  
                return null;  
            }  
        }  
        try {  
            responseBody = new String(baos.toByteArray(), encoding);  
        } catch (UnsupportedEncodingException e) {  
            return null;  
        } finally {  
            if (httpCon != null) {  
                httpCon.disconnect();  
            }  
            if (baos != null) {  
                try {  
                    baos.close();  
                } catch (IOException e) {  
                }  
            }  
        }  

        return responseBody;  
    }  
}  

3.第三种方式

import java.io.IOException;  

import org.apache.http.HttpEntity;  
import org.apache.http.HttpResponse;  
import org.apache.http.client.ClientProtocolException;  
import org.apache.http.client.ResponseHandler;  
import org.apache.http.client.methods.HttpGet;  
import org.apache.http.impl.client.CloseableHttpClient;  
import org.apache.http.impl.client.HttpClients;  
import org.apache.http.util.EntityUtils;  

/** 
 * 根据httpclient进行访问 
 * @author Administrator 
 * 
 */  
public class HttpUtils {  


    /** 
     * 访问url方法 
     *  
     * @param url 
     * @return 
     */  
    public static String callOnHttp(String url) {  

        String address = "";  
        CloseableHttpClient httpclient = HttpClients.createDefault();  
        try {  
            HttpGet httpget = new HttpGet(url);  
            ResponseHandler<String> responseHandler = new ResponseHandler<String>() {  
                public String handleResponse(final HttpResponse response)  
                        throws ClientProtocolException, IOException {  
                    int status = response.getStatusLine().getStatusCode();  
                    if (status >= 200 && status < 300) {  
                        HttpEntity entity = response.getEntity();  
                        return entity != null ? EntityUtils.toString(entity)  
                                : null;  
                    } else {  
                        throw new ClientProtocolException(  
                                "Unexpected response status: " + status);  
                    }  
                }  
            };  
            address = httpclient.execute(httpget, responseHandler);  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                httpclient.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return address;  
    }  
}  

转自:原文

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java可以使用HTTPClient和HttpURLConnection两种方式来实现GET和POST请求。 使用HTTPClient的方法有两个版本,分别是HTTPClient3.1和HTTPClient4.5.5。HTTPClient3.1位于org.apache.commons.httpclient包下,而HTTPClient4.5.5位于org.apache.http.client包下。这两个版本都提供了对远程URL的操作工具包,可以满足工作需求。 另一种方式是使用HttpURLConnection,它是Java的标准请求方式。可以通过创建HttpURLConnection对象来发送GET和POST请求,并获取响应结果。 以下是使用HTTPClient和HttpURLConnection实现GET和POST请求的示例代码: 使用HTTPClient3.1实现GET请求: ```java HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); int statusCode = client.executeMethod(method); String response = method.getResponseBodyAsString(); ``` 使用HTTPClient4.5.5实现GET请求: ```java CloseableHttpClient client = HttpClients.createDefault(); HttpGet request = new HttpGet(url); CloseableHttpResponse response = client.execute(request); String result = EntityUtils.toString(response.getEntity()); ``` 使用HttpURLConnection实现GET请求: ```java URL url = new URL("http://example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); ``` 使用HTTPClient4.5.5实现POST请求: ```java CloseableHttpClient client = HttpClients.createDefault(); HttpPost request = new HttpPost(url); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("param1", "value1")); params.add(new BasicNameValuePair("param2", "value2")); request.setEntity(new UrlEncodedFormEntity(params)); CloseableHttpResponse response = client.execute(request); String result = EntityUtils.toString(response.getEntity()); ``` 使用HttpURLConnection实现POST请求: ```java URL url = new URL("http://example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write("param1=value1&param2=value2"); writer.flush(); int responseCode = connection.getResponseCode(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); ``` 以上是使用Java实现GET和POST请求的方法,可以根据具体需求选择适合的方式来发送请求并获取响应结果。\[1\]\[2\] #### 引用[.reference_title] - *1* [用Java实现GET,POST请求](https://blog.csdn.net/lianzhang861/article/details/80364549)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [JAVA的GET和POST请求实现方式](https://blog.csdn.net/u012513972/article/details/79569888)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值