import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class JHttpURLConnection {
public static String getHttpResults(String targetUrl, String parameter, String contentType) {
String result = "";
URL url;
BufferedReader in = null;
InputStreamReader isr = null;
OutputStream out = null;
try {
url = new URL(targetUrl);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
byte[] b = null;
if(!"".equals(parameter)) {
b = parameter.getBytes("UTF-8");
httpConn.setRequestProperty("Content-Length", String.valueOf(b.length));
}
String cType = "text/xml; charset=utf-8";
if(contentType != null && !"".equals(contentType)) {
cType = contentType;
}
httpConn.setRequestProperty("Content-Type", cType);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
if(!"".equals(parameter)) {
out = httpConn.getOutputStream();
out.write(b);
}
isr = new InputStreamReader(httpConn.getInputStream(), "utf-8");
in = new BufferedReader(isr);
String inputLine = "AA";
StringBuffer message = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
message.append(inputLine);
}
httpConn.disconnect();
result = message.toString();
} catch (MalformedURLException e) {
result = "
+ e.getMessage()
+ "
} catch (IOException e) {
result = "
+ e.getMessage()
+ "
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
result = "
+ e.getMessage()
+ "
}
try {
if (isr != null) {
isr.close();
}
} catch (IOException e) {
result = "
+ e.getMessage()
+ "
}
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
result = "
+ e.getMessage()
+ "
}
}
return result;
}
public static void main(String[] args) {
System.out.println(getHttpResults("http://www.naver.com", "", "text/html; charset=utf-8"));
}
}