请求参数的java类
import java.sql.Timestamp;
public class ReqData {
private String appKey;
private String sign;
private String version;
private long salt;
public String getAppKey() {
return appKey;
}
public void setAppKey(String appKey) {
this.appKey = appKey;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public long getSalt() {
return salt;
}
public void setSalt(long salt) {
this.salt = salt;
}
}
实现调用接口,获得参数的方法
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.junit.Test;
public class HttpInvoker {
public static final String GET_URL = "http://hdsoutlet.qunar.com/api/hotel/queryHotelList.json";
//http通过get方法调用接口
public static void readContentFromGet() throws IOException, ParseException{
Date epoch = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse("01/01/1970 08:02:03");
long t=epoch.getTime()/1000;
ReqData r=new ReqData();
r.setAppKey("12345678");
r.setSign("063cae89a00896187f80eecbf922364a");
r.setVersion("3.1.0");
r.setSalt(t);
JSONObject json=new JSONObject();
JSONObject member1 = new JSONObject();
member1.put("appKey", r.getAppKey());
member1.put("salt", r.getSalt());
member1.put("sign", r.getSign());
member1.put("version", r.getVersion());
json.put("head", member1);
//拼凑get请求的字符串
String getURL=GET_URL+"?reqData="+json;
URL getUrl =new URL(getURL);
//根据拼凑的URL打开连接,URL.openConnection函数会根据URL的类型
// 返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
// 进行连接,但是实际上get request要在下一句的connection.getInputStream()函数中才会真正发到
// 服务器
connection.connect();
//取得输入流,并使用Reader读取
BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
System.out.println("------------------------------");
System.out.println("Contents of get request");
System.out.println("------------------------------");
String lines;
while((lines=reader.readLine())!=null){
System.out.println(lines);
}
reader.close();
//断开连接
connection.disconnect();
System.out.println("------------------------------");
System.out.println("Contents of get request");
System.out.println("------------------------------");
}
}