研发闲暇时间,把开发过程中较好的代码段备份一下,如下的代码内容是关于Java处理HTTP请求的相关的代码,应该是对各朋友有好处。
package com.http.tool;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Pattern;
public class HttpTool {
public String sendGetData(String get_url, String content) throws Exception {
String result = "";
URL getUrl = null;
BufferedReader reader = null;
String lines = "";
HttpURLConnection connection = null;
try {
if (content != null && !content.equals(""))
get_url = get_url + "?" + content;
getUrl = new URL(get_url);
connection = (HttpURLConnection) getUrl.openConnection();
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection
while ((lines = reader.readLine()) != null) {
result = result + lines;
}
return result;
} catch (Exception e) {
throw e;
} finally {
if (reader != null) {
reader.close();
reader = null;
}
connection.disconnect();
}
}
public String sendPostData(String POST_URL, String content)
throws Exception {
HttpURLConnection connection=null;
DataOutputStream out=null;
BufferedReader reader=null;
String line = "";
String result="";
try {
URL postUrl = new URL(POST_URL);
connection= (HttpURLConnection) postUrl.openConnection();
connection.setRequestMethod("POST");
connection.setInstanceFollowRedirects(true);
"application/x-www-form-urlencoded");
connection.connect();
out.writeBytes(content);
String content =
"name=" + URLEncoder.encode ("Hitesh Agrawal") +
"&profession=" + URLEncoder.encode ("Software Engineer");
out.flush();
reader = new BufferedReader(new InputStreamReader(
while ((line = reader.readLine()) != null) {
result=result+line;
}
return result;
} catch (Exception e) {
throw e;
}finally
{
if(out!=null)
{
out.close();
out=null;
}
if(reader!=null)
{
reader.close();
reader=null;
}
connection.disconnect();
}
}
public static String htmlFilter(String inputString) {
String textStr = "";
java.util.regex.Pattern p_script;
java.util.regex.Matcher m_script;
try {
String regEx_hrefjs="href=javascript:";
htmlStr = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
htmlStr=Pattern.compile(regEx_onevent, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
htmlStr=Pattern.compile(regEx_hrefjs, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
htmlStr=Pattern.compile(regEx_iframe, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
htmlStr=Pattern.compile(regEx_link, Pattern.CASE_INSENSITIVE).matcher(htmlStr).replaceAll("");
textStr = htmlStr;
} catch (Exception e) {
System.err.println("Html2Text: " + e.getMessage());
}
return textStr;
}
public static void main(String[] args){
HttpTool ht = new HttpTool();
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}