http请求大致步骤:
①.有代理先设置代理
②.获取url
③.获取HttpURLConnection连接
④.设置请求方式
⑤.其他设置
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
⑥.通过输入输出流传递数据
⑦.返回得到数据(返回的时候记着设置编码格式)
POST方法案例:package com.cn.zxs;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class TestPost2 {
public static String getJsonFromPost(String path,String param) throws IOException{
try {
//System.setProperty("http.proxyHost", "proxy.cmcc"); //有代理需要设置代理
//System.setProperty("http.proxyPort", "8080");
URL url = new URL(path.toString());//获取url
HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
httpcon.setRequestMethod("POST");//设置http请求方式,不能小写,小写会报错
httpcon.setDoInput(true);
httpcon.setDoOutput(true);
PrintWriter prt = new PrintWriter(httpcon.getOutputStream());
prt.write(param);
prt.flush();
BufferedInputStream bis = new BufferedInputStream(httpcon.getInputStream());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[1024];
if(-1!=(len=bis.read(buffer))){
baos.write(buffer, 0, len);
baos.flush();//flush输出流的缓冲
}
baos.close();
return baos.toString("utf-8");//返回数据并设置编码格式,防止返回数据乱码
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws IOException {
Map<String, String> map = new HashMap<String, String>();
map.put(参数名, 参数值);
String str = getJsonFromPost("请求数据源网址",map.toString());//调用上面静态方法
System.out.println(str);
}
}
GET方法案例:
package com.cn.zxs;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class TestGet {
public static String getJsonFromHttp(String path) throws IOException{
System.setProperty("http.proxyHost", "proxy.cmcc");//网络有代理的需要设置
System.setProperty("http.proxyPort", "8080");
try {
URL url = new URL(path.toString());//获取URL
HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();//获取链接
httpconn.setRequestMethod("GET");//设置请求方式区分大小写,千万不能小写,不然会报错
//通过输入输出流对数据进行返回
if (200==httpconn.getResponseCode()){
InputStream is = httpconn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0 ;
while(-1!=(len=is.read(buffer))){
baos.write(buffer, 0, len);
baos.flush();
}
return baos.toString("utf-8");//返回的时候设置编码格式,预防得到数据乱码
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws IOException {
String str = getJsonFromHttp("http://api.huceo.com/social/?key=&num=10");//调用上面静态方法进行get请求
System.out.println(str);
}
}