package com.kompasim.utils;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpUtil {
String path = null;
URL url = null;
HttpURLConnection urlConnection = null;
private String resultData = "";
public HttpUtil(String p){
path = p;
}
public void open(String string){
try {
url = new URL(path + "?" + string);
System.out.println("url is : " + url);
urlConnection = (HttpURLConnection)url.openConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
public void setHeader(String name, String value){
urlConnection.addRequestProperty(name,value);
}
public String get(){
try {
urlConnection.setRequestMethod("GET");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout (5000);
urlConnection.connect();
if (urlConnection.getResponseCode()!=200){
System.out.println("err : get网络请求失败,返回200");
return "error";
}else {
InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader br = new BufferedReader(isr);
String line = null;
while((line=br.readLine())!=null){
resultData += line;
}
isr.close();
br.close();
urlConnection.disconnect();
return resultData.toString();
}
}catch (Exception e){
e.printStackTrace();
System.out.println("err : " + e.getStackTrace().toString());
return "error";
}
}
public String post(String encodedString){
try {
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setConnectTimeout(5*1000);
}catch (Exception e){
System.out.println("err : " + e.getStackTrace().toString());
}
try{
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
urlConnection.connect();
DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
out.writeBytes(encodedString);
out.flush();
out.close();
if (urlConnection.getResponseCode()!=200){
System.out.println("err : post网络请求失败,返回200");
return "error";
}else {
InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream());
BufferedReader br = new BufferedReader(isr);
String line = null;
while((line=br.readLine())!=null){
resultData += line;
}
isr.close();
urlConnection.disconnect();
return resultData.toString();
}
}catch(Exception e){
System.out.println("err : " + e.getStackTrace().toString());
return "error";
}
}
}