baihuitestsoftware

一、先创建一个实现get post方法的类。

package com.baihui.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpRequest {

    /**
     * sendGet
     * 
     * @param getUrl
     * @return body
     */

    public String sendGet(String getUrl) {
        String body = "", line = "";
        try {
            URL url = new URL(getUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setUseCaches(false);
            conn.setRequestProperty("Canche-Control", "no-cache");
            conn.connect();

            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            while ((line = br.readLine()) != null) {
                body += line;
            }
            System.out.println(body);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return body;
    }

    /**
     * sendPost
     * 
     * @param postUrl
     * @param postParam
     * @return
     */
    public String sendPost(String postUrl, String postParam) {
        String body = "", line = "";
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(postUrl);
            urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setUseCaches(false);
            urlConnection.setInstanceFollowRedirects(false);
            urlConnection.setRequestProperty("cookie", "");
            urlConnection.connect();

            PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
            out.print(postParam);
            out.flush();

            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
            while ((line = in.readLine()) != null) {
                body += "\n" + line;
            }
            urlConnection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return body;

    }

}

 

分类:

技术点:

相关文章: