package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wasu.upm.client.util.LogUtils;
public class HttpUtils {
private static Log log =LogUtils.getBaseLog();
public static synchronized String httpGet(String url) {
HttpClient hc = new HttpClient();
// 配置代理
// if ("1".equals(ConfigReader.getBaseConfig("isSetProxy").trim())) {
// hc.getHostConfiguration().setProxy(ConfigReader.getBaseConfig("proxyHost").trim(), Integer.valueOf(ConfigReader.getBaseConfig("proxyPort").trim()));
// hc.getParams().setAuthenticationPreemptive(true);
// hc.getState().setProxyCredentials(AuthScope.ANY,
// new UsernamePasswordCredentials(ConfigReader.getBaseConfig("username").trim(), ConfigReader.getBaseConfig("pwd").trim()));
// }
GetMethod method = new GetMethod(url);
method.setRequestHeader("X-ATAcq-Protocol-Version", "1.0");
//method.addRequestHeader("Cookie", LoginProcessor.getSessionId());//session验证信息
StringBuffer result = new StringBuffer();
try {
int statusCode = hc.executeMethod(method);
//System.out.println("站点请求状态:"+statusCode);
if (statusCode == HttpStatus.SC_OK) {
BufferedReader body = new BufferedReader(new InputStreamReader(
method.getResponseBodyAsStream(), "UTF-8"));
String s = "";
while ((s = body.readLine()) != null) {
result.append(s);
}
body.close();
// System.out.println("站点集合:"+result.toString());
} else {
}
} catch (Exception e) {
log.error("HTTP请求错误", e);
}finally{
method.releaseConnection();
}
return result.toString();
}
public static void main(String[] args) {
String str = httpGet("http://125.210");
JSONArray array = JSONObject.parseArray(str);
JSONObject o= (JSONObject) array.get(0);
System.out.println(o.get("siteCode"));
System.out.println(o.get("siteName"));
}
}
java http请求
最新推荐文章于 2024-09-15 09:47:04 发布