欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

http get post 请求

程序员文章站 2022-04-15 12:40:33
...
package com.fh.util;

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.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;

public class HTTPServerUtil {
	
	
	public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

	public static String doPostRequest(String servletAddress,Object content){
//        PrintWriter out = null;
        BufferedReader in = null;
        String newStr = "";
        try {
            content = new String(content.toString().getBytes("utf-8"), "utf-8");
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }  
        System.out.println(newStr);
        String resoult = "";
        DataOutputStream outData = null;
        try {
        	System.out.println("要发送的信息是:"+content);
            /*拼接url,Android这里需要换上远程地址,因为Android端没办法访问localhost,java的话本地tomcat运行的话倒是无妨*/
            URL url = new URL(servletAddress);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            //这两个参数必须加
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestProperty("contentType", "GBK");  
            //设置超时时间
            httpURLConnection.setReadTimeout(1000*1000);
            httpURLConnection.setConnectTimeout(1000*1000);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.connect();
            outData =  new DataOutputStream(httpURLConnection.getOutputStream());
            outData.write(content.toString().getBytes("utf-8"));
            outData.flush();
            if(httpURLConnection.getResponseCode() == 200){
                in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(),"utf-8"));
                String line;
                while((line=in.readLine())!=null){
                    resoult+=line;
                }
            }
            System.out.println("服务器返回的结果是:"+resoult);
            return resoult;
        } catch (MalformedURLException e) {
        	System.out.println("URL异常");
            e.printStackTrace();
        } catch (IOException e) {
        	System.out.println("IO异常");
            e.printStackTrace();
        }finally {
            try{
              if(outData!=null) {
              outData.close();
              }
                if(in!=null)
                    in.close();
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
	
	public static String doPostJson(String url,String key,String json){
	    try {
	        String postURL=url;
	        PostMethod postMethod = null;
	        postMethod = new PostMethod(postURL) ;
	        postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
	        postMethod.addParameter(key,json);  //传参数
	        HttpClient httpClient = new HttpClient();
	        int response = httpClient.executeMethod(postMethod); // 执行POST方法
	        String result = postMethod.getResponseBodyAsString() ;
	        return result;
	    } catch (Exception e) {
	        throw new RuntimeException(e.getMessage());
	    }
	}

}

 

相关标签: java http请求