java实现http的get与post方法

  • Post author:
  • Post category:java


package com.jerome;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.HttpURLConnection;

import java.net.URL;

public class JavaHttpMethod {



public static void main(String[] args) {



// TODO Auto-generated method stub

JavaHttpMethod jhh=new JavaHttpMethod();

//  jhh.sendGet(“https://www.sohu.com”);

jhh.sendPost(“http://localhost:8080/index.jsp”,”helloworld” );



}



public void sendGet(String urlAddress){



try {



//建立链接



HttpURLConnection urlConnection=null;



URL url=new URL(urlAddress);



urlConnection =(HttpURLConnection) url.openConnection();



urlConnection.setReadTimeout(5000);



urlConnection.setReadTimeout(5000);



urlConnection.setUseCaches(false);



urlConnection.setRequestProperty(“cookie”,”x=y”);



urlConnection.connect();






//获取请求内容



BufferedReader br= new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),”utf-8″));



String text=br.readLine();



while(text!=null){



System.out.println(text);



text=br.readLine();



}



} catch (Exception e) {



// TODO Auto-generated catch block



e.printStackTrace();



}



}






public void sendPost(String urlAddress,String paramValue){



try {



//建立链接



HttpURLConnection urlConnection=null;



URL url=new URL(urlAddress);



urlConnection =(HttpURLConnection) url.openConnection();



urlConnection.setDoOutput(true);



urlConnection.setReadTimeout(5000);



urlConnection.setReadTimeout(5000);



urlConnection.setUseCaches(false);



urlConnection.setRequestProperty(“cookie”,”x=y”);



urlConnection.connect();





//获取请求内容



PrintWriter pw=new PrintWriter(urlConnection.getOutputStream());



pw.print(paramValue);



pw.flush();//将参数传入服务器。





BufferedReader br=new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));



String text=br.readLine();



while(text!=null){



System.out.println(text);



text=br.readLine();



}



//打印的是apache tomcat的页面的源码 不是index.jsp页面的源码



} catch (Exception e) {



// TODO Auto-generated catch block



e.printStackTrace();



}



}

}



版权声明:本文为AngeloWolf原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。