public HttpURLConnection getHttpConnection(String url, String type){
URL uri = null;
HttpURLConnection con = null;
try{
uri = new URL(url);
con = (HttpURLConnection) uri.openConnection();
con.setRequestMethod(type);
con.setDoOutput(true);
con.setDoInput(true);
con.setConnectTimeout(60000);
con.setReadTimeout(60000);
con.setRequestProperty("Accept-Encoding", "Your Encoding");
con.setRequestProperty("Content-Type", "Your Encoding");
}catch(Exception e){
logger.info( "connection i/o failed" );
}
return con;
}
Następnie w swoim kodzie:
public void yourmethod(String url, String type, String reqbody){
HttpURLConnection con = null;
String result = null;
try {
con = conUtil.getHttpConnection( url , type);
if( reqbody != null){
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream out = new DataOutputStream(con.getOutputStream());
out.writeBytes(reqbody);
out.flush();
out.close();
}
con.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String temp = null;
StringBuilder sb = new StringBuilder();
while((temp = in.readLine()) != null){
sb.append(temp).append(" ");
}
result = sb.toString();
in.close();
} catch (IOException e) {
e.printStackTrace();
logger.error(e.getMessage());
}
}