序:
http 请求是后台经常使用的技术,以下是请求的两种方式,亲测有效,代码直接复制黏贴可用。
一、原生态HTTP请求方式
package httpTest;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class HttpTest {
public static final String GET_URL = "http://112.4.27.9/mall-back/if_user/store_list?storeId=32";
public static final String POST_URL = "http://112.4.27.9/mall-back/if_user/store_list";
/**
*
* 接口调用 GET
*/
public static void httpURLConectionGET(String getURL) {
try {
URL url = new URL(getURL); // 把字符串转换为URL请求地址
HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
connection.connect();// 连接会话
// 获取输入流
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {// 循环读取流
sb.append(line);
}
br.close();// 关闭流
connection.disconnect();// 断开连接
System.out.println("POST 返回内容 = "+ sb.toString());
} catch (Exception e) {
e.printStackTrace();
System.out.println("GET 失败!");
}
}
/**
*
* 接口调用 POST
*/
public static void httpURLConnectionPOST(String postURL) {
try {
URL url = new URL(postURL);
// 将url 以 open方法返回的urlConnection 连接强转为HttpURLConnection连接
// (标识一个url所引用的远程对象连接)
HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 此时cnnection只是为一个连接对象,待连接中
// 设置连接输出流为true,默认false (post 请求是以流的方式隐式的传递参数)
connection.setDoOutput(true);
// 设置连接输入流为true
connection.setDoInput(true);
// 设置请求方式为post
connection.setRequestMethod("POST");
// post请求缓存设为false
connection.setUseCaches(false);
// 设置该HttpURLConnection实例是否自动执行重定向
connection.setInstanceFollowRedirects(true);
// 设置请求头里面的各个属性 (以下为设置内容的类型,设置为经过urlEncoded编码过的from参数)
// application/x-javascript text/xml->xml数据
// application/x-javascript->json对象
// application/x-www-form-urlencoded->表单数据
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 建立连接
// (请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
connection.connect();
// 创建输入输出流,用于往连接里面输出携带的参数,(输出内容为?后面的内容)
DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());
String parm = "storeId=" + URLEncoder.encode("32", "utf-8"); // URLEncoder.encode()方法,
// 为字符串进行编码
// 将参数输出到连接 ---传参数
dataout.writeBytes(parm);
// 输出完成后刷新并关闭流
dataout.flush();
dataout.close(); // 重要且易忽略步骤 (关闭流,切记!)
int state = connection.getResponseCode();
System.out.println("状态码" + state ); // 200 成功
// 连接发起请求,处理服务器响应 (从连接获取到输入流并包装为bufferedReader)
BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder sb = new StringBuilder(); // 用来存储响应数据
// 循环读取流,若不到结尾处
while ((line = bf.readLine()) != null) {// 循环读取流
sb.append(line);
}
bf.close(); // 重要且易忽略步骤 (关闭流,切记!)
connection.disconnect(); // 销毁连接
System.out.println("POST 返回内容 = "+sb.toString());
} catch (Exception e) {
e.printStackTrace();
System.out.println("POST 失败!");
}
}
public static void main(String[] args) {
httpURLConectionGET(GET_URL);
httpURLConnectionPOST(POST_URL);
}
}
二、HttpClient 请求
HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。
下载地址: http://hc.apache.org/downloads.cgi
package httpTest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
@SuppressWarnings("deprecation")
public class HttpClientTest {
public static final String GET_URL = "http://112.4.27.9/mall-back/if_user/store_list?storeId=32";
public static final String POST_URL = "http://112.4.27.9/mall-back/if_user/store_list";
public static void main(String[] args) {
httpGet(GET_URL);
httpPost(POST_URL);
}
private static void httpPost(String url){
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<BasicNameValuePair> list = new ArrayList<>();
list.add(new BasicNameValuePair("storeId","32"));
try {
post.setEntity(new UrlEncodedFormEntity(list));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String str = EntityUtils.toString(entity);
System.out.println(str);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void httpGet(String url){
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
try {
HttpResponse response = client.execute(get);
String str = EntityUtils.toString(response.getEntity());
System.out.println(str);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
参考:http://blog.csdn.net/wangpeng047/article/details/19624529