Hello, i would like some enlightment with my project.
I am trying to create a class that will be able to create and sent http requests (GET of POST). I also want it to be able to change some http headers and sent the request. I am a bit confused about the order in which the statements should be executed to have the results. For example i saw some tutorials put first open connection and then set the request type.
I thought the order should be set request type,set headers, openconnection.
I am using the HttpURLConnection.
Here is what i have done so far:
import java.net.*; import java.io.*; public class HTTP { private String - Pastebin.com
import java.net.*; import java.io.*; public class HTTP { private String baseURL; private String path; private String fullPath; private HttpURLConnection http; public HTTP(String url){ this.fullPath=url.indexOf("http://")==0?url:"http://".concat(url); this.baseURL=getBaseUrl(url); this.path=""; this.openConnection(); } public void addHeaders(String[] headers,String values){ for(int i=0;i<headers.length;i++); } public void changePath(String path){ this.path=path; this.fullPath=this.baseURL.concat(path); this.openConnection(); } public static String getBaseUrl(String url){ String val="http://"; if(!url.contains("http://")) url="http://".concat(url); String results[]=url.split("/"); if(results.length>=3) return val.concat(results[2]); return ""; } private void openConnection(){ try { URL u = new URL(this.fullPath); this.http = (HttpURLConnection) u.openConnection(); }catch (MalformedURLException ex) { System.err.println(this.fullPath + " is not a URL I understand"); }catch (IOException ex) { System.err.println(ex); } } public void setHeader(String header,String value){ this.http.setRequestProperty(header, value); } public void addHeader(String header,String value){ this.http.addRequestProperty(header, value); } public void printHeaders(){ for (int j = 1; ; j++) { String header = this.http.getHeaderField(j); String key = this.http.getHeaderFieldKey(j); if (header == null || key == null) break; System.out.println(this.http.getHeaderFieldKey(j) + ": " + header); } } public static void main(String[] args) { HTTP h=new HTTP("http://google.com/agsa"); h.setHeader("Referer", "wwwa.ga.a"); h.printHeaders(); } }