1.URLConnection请求
get请求 地址后面挂参数就好撒
String url = “https://www.baidu.com/?userName=zhangsan&password=123456”;
URL url = new URL(url);
//得到connection对象。
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置请求方式
connection.setRequestMethod(“GET”);
//连接
connection.connect();
//得到响应码
int responseCode = connection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
//得到响应流
InputStream inputStream = connection.getInputStream();
//将响应流转换成字符串
String result = is2String(inputStream);//将流转换为字符串。
Log.d(“kwwl”,“result=============”+result);
}
post传参
public static String post(String interfaceUrl, Map<String, String> headers, String queryString) throws IOException {
URL url = new URL(interfaceUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod(“POST”);
con.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded; charset=utf-8”);
con.setDoOutput(true);
con.setConnectTimeout(DEFAULT_TIMEOUT);
con.setReadTimeout(DEFAULT_TIMEOUT);
for (Map.Entry<String, String> e : headers.entrySet()) {
con.setRequestProperty(e.getKey(), e.getValue());
}
DataOutputStream out = null;
BufferedReader in = null;
try {
out = new DataOutputStream(con.getOutputStream());
out.write(queryString.getBytes(Charset.forName("UTF-8")));
out.flush();
in = new BufferedReader(
new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
return content.toString();
} finally {
if (out != null) {
try {
out.close();
} catch (Exception ignored) {
}
}
if (in != null) {
try {
in.close();
} catch (Exception ignored) {
}
}
}
}
2.HttpClient
post json传参数 get的话换成httpget就行 大径相同
/**
* 发送post请求方法
* @param url 接口地址
* @param json 请求参数
* @return
*/
public static String tpostNoEncode(String url, String json){
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
StringBuffer sb = new StringBuffer();
try {
StringEntity se = new StringEntity(json, Charset.forName("utf-8"));
se.setContentEncoding("UTF-8");
post.setEntity(se);
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
org.apache.http.HttpResponse res = client.execute(post);
org.apache.http.HttpEntity entity = res.getEntity();
InputStream instream = entity.getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(
instream, "UTF-8"));
String data = "";
while ((data = in.readLine()) != null) {
sb.append(data);
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return sb.toString();
}
以上都是比较简单的例子
主要是和三方对接的认证什么的 比如信任证书,token,账号密码登录啥的