commons.httpclient练习
public class HttpClientTest {
public static void main(String[] args) {
// testGet();
testPost();
}
private static void testPost() {
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30 * 1000);
PostMethod postMethod = new PostMethod(AppConfig.LOGIN_URL);
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 30 * 1000);
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
// 对应的是form表单的方式,但是不能有该方式的请求头,否则 请求报错
// 添加请求参数方式一
// NameValuePair userNameNVA = new NameValuePair("username", "zzgtest02");
// NameValuePair pwdNAV = new NameValuePair("password", "123456");
// NameValuePair[] nameValuePairs = new NameValuePair[2];
// nameValuePairs[0] = userNameNVA;
// nameValuePairs[1] = pwdNAV;
// postMethod.addParameters(nameValuePairs);
// 添加请求参数方式二
// postMethod.addParameter("username","zzgtest02");
// postMethod.addParameter("password","123456");
HashMap<String, String> loginRequestParams = AppConfig.getLoginRequestParams();
if (loginRequestParams != null && loginRequestParams.size() > 0) {
for (Map.Entry<String, String> entry : loginRequestParams.entrySet()) {
postMethod.addParameter(entry.getKey(), entry.getValue());
}
}
try {
int statusCode = httpClient.executeMethod(postMethod);
if (statusCode != HttpStatus.SC_OK) {
System.out.println("请求出错 : " + postMethod.getStatusLine());
return;
}
// 方式三、postMethod.getResponseBodyAsStream(); 读取为InputStream,在网页内容数据量大时候推荐使用
InputStream inputStream = postMethod.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
stringBuffer.append(str);
}
System.out.println(stringBuffer.toString());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private static void testGet() {
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30 * 1000);
GetMethod getMethod = new GetMethod(AppConfig.BANNER_URL);
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 30 * 1000);
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
try {
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
System.out.println("请求出错 : " + getMethod.getStatusLine());
return;
}
// 方式一、读取为字节数组
// byte[] responseBody = getMethod.getResponseBody();
// String s = new String(responseBody);
// System.out.println(s);
// 方式二、String responseBodyAsString = getMethod.getResponseBodyAsString();
// System.out.println(responseBodyAsString);
// 方式三、getMethod.getResponseBodyAsStream(); 读取为InputStream,在网页内容数据量大时候推荐使用
InputStream inputStream = getMethod.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
String str = "";
while ((str = br.readLine()) != null) {
stringBuffer.append(str);
}
System.out.println(stringBuffer.toString());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
HttpUrlConnection练习
public class HttpURLConnectionTest {
public static void main(String[] args) {
// testGet();
testPost();
}
private static void testPost() {
StringBuffer sb = new StringBuffer();
BufferedReader bufferedReader = null;
InputStream is = null;
HttpURLConnection urlConnection = null;
DataOutputStream dataOutputStream = null;
OutputStream outputStream = null;
try {
// 创建连接
URL url = new URL(AppConfig.LOGIN_URL);
urlConnection = (HttpURLConnection) url.openConnection();
// 设置请求方式
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(30 * 1000);
urlConnection.setReadTimeout(30 * 1000);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// //DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
// 设置是否向httpUrlConnection输出,即是否允许向服务器传递参数
urlConnection.setDoOutput(true);
// 设置是否可读取
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
HashMap<String, String> loginRequestParams = AppConfig.getLoginRequestParams();
// 设置参数
if (loginRequestParams != null && loginRequestParams.size() > 0) {
outputStream = urlConnection.getOutputStream();
// outputStream.write(createLinkString(loginRequestParams).getBytes());
dataOutputStream = new DataOutputStream(outputStream);
dataOutputStream.write(createLinkString(loginRequestParams).getBytes());
dataOutputStream.flush();
dataOutputStream.close();
}
// 获取响应数据
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
is = urlConnection.getInputStream();
if (is != null) {
bufferedReader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
outputStream = null;
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
dataOutputStream = null;
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
is = null;
}
}
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
bufferedReader = null;
}
// 断开连接
urlConnection.disconnect();
}
System.out.println(sb.toString());
}
/**
* 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
*
* @param params 需要排序并参与字符拼接的参数组
* @return 拼接后字符串
*/
public static String createLinkString(Map<String, String> params) {
List<String> keys = new ArrayList<>(params.keySet());
Collections.sort(keys);
StringBuilder prestr = new StringBuilder();
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
String value = params.get(key);
if (i == keys.size() - 1) {// 拼接时,不包括最后一个&字符
prestr.append(key).append("=").append(value);
} else {
prestr.append(key).append("=").append(value).append("&");
}
}
return prestr.toString();
}
private static void testGet() {
StringBuffer sb = new StringBuffer();
BufferedReader bufferedReader = null;
InputStream is = null;
HttpURLConnection urlConnection = null;
try {
// 创建连接
URL url = new URL(AppConfig.BANNER_URL);
urlConnection = (HttpURLConnection) url.openConnection();
// 设置请求方式
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(30 * 1000);
urlConnection.setReadTimeout(30 * 1000);
// 开始连接
urlConnection.connect();
// 获取响应数据
if (urlConnection.getResponseCode() == 200) {
is = urlConnection.getInputStream();
if (is != null) {
bufferedReader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
is = null;
}
}
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
bufferedReader = null;
}
// 断开连接
urlConnection.disconnect();
}
System.out.println(sb.toString());
}
}
okhttp练习
public class OkHttpTest {
public static void main(String[] args) {
OkHttpClient okHttpClient = getOkHttpClient();
// testGetMethod(okHttpClient);
testPostMethod(okHttpClient);
}
private static void testPostMethod(OkHttpClient okHttpClient) {
// form表单方式提交
FormBody formBody = new FormBody.Builder().add("username", "zzgtest02").add("password", "123456").build();
Request request = new Request.Builder()
.url(AppConfig.LOGIN_URL)
.post(formBody)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
System.out.println(result);
String jsonStr = JSON.toJSONString(result);
System.out.println(jsonStr);
}
});
}
private static void testGetMethod(OkHttpClient okHttpClient) {
Request request = new Request.Builder()
.url(AppConfig.BANNER_URL)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
System.out.println(result);
String jsonStr = JSON.toJSONString(result);
System.out.println(jsonStr);
}
});
}
private static OkHttpClient getOkHttpClient() {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.connectTimeout(30, TimeUnit.SECONDS)
.build();
return okHttpClient;
}
}