接口调用方法,这里返回的是JSONObject:
public JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
/*
JSONObject jsonObject = null;
try {
final URL url = new URL(requestUrl);
//创建代理服务器
InetSocketAddress addr = new InetSocketAddress("dl-proxy.neusoft.com", 8080);
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); //http代理
Authenticator.setDefault(new MyAuthenticator("liuxinyi", "N@6228279liu")); //设置代理的用户和密码
final HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy); //设置代理访问
//不用代理
final HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
//设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("Content-Type", "text/html;charset=utf-8");
//当outputStr不为null时向输出流写数据
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
//从输入流读取返回内容
final BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = br.readLine()) != null) {
buffer.append(str);
}
//释放资源
br.close();
conn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
}catch (ConnectException ce) {
ce.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
*/
JSONObject jsonObject = null;
try {
HttpClient client = new HttpClient();
HttpMethod httpMethod = null;
if ("get".equalsIgnoreCase(requestMethod) || StringUtils.isBlank(requestMethod)) {
httpMethod = new GetMethod(requestUrl);
} else if ("post".equalsIgnoreCase(requestMethod)) {
httpMethod = new PostMethod(requestUrl);
((PostMethod)httpMethod).setRequestBody(outputStr);
}
httpMethod.setRequestHeader("Content-Type", "text/html;charset=utf-8");
int code = client.executeMethod(httpMethod);
if (code == 200) {
jsonObject = JSONObject.fromObject(httpMethod.getResponseBodyAsString());
}
httpMethod.releaseConnection();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}