本文件介紹在需要通過代理才能訪問外網的情況下如何以純Java實現發起HTTP的請求。此部分內容與上一篇博客內容大同小異,只有兩處稍有不同。
1.準備需要的Jar包
需要的jar包與上一篇介紹的相同,包括:commons-httpclient-3.1.jar,commons-logging-1.1.1.jar,commons-codec-1.3.jar以及json-rpc-1.0.jar。
2.開始編碼
2.1創建HTTPClient對象
HttpClient client=new HttpClient();
2.2設置代理服務器IP及代理服務器的端口(此處是與前一篇第一處不同點)
client.getHostConfiguration().setProxy(proxyHostIP, proxyPort);
2.3組裝URL生成HttpMethod對象,真實的目標主機、目標主機的端口號組裝到url字符串當中(此處是與前一篇第二處不同點)
String url="http://"+hostIP+":"+port+"/ysInterfaceServe/flowRecharge_v1.cgi?terminalID="+terminalID
+"&factoryID="+factoryID
+"&reqDateTime="+reqDate
+"&sign="+new String(sign).toLowerCase()
+"&requestMsg="+resMsg;
HttpMethod method = new GetMethod(url);
2.4發起HTTP請求
client.executeMethod(method);
2.5獲取HTTP請求的響應信息
String response = method.getResponseBodyAsString();
2.6通過JSONObject對象解析HTTP的響應信息
JSONObject json=new JSONObject(response);
System.out.println("key: status"+" "+"values:"+json.getString("status"));
2.7釋放HTTP請求
method.releaseConnection();
到此爲止,java如何發起HTTP請求簡述完畢!