HttpGet 请求
package com.ucsoft.bas.service;
import java.net.HttpURLConnection;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
HttpClient httpClient = new DefaultHttpClient();
String strResult = "";
try {
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, -1);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = sdf.format(cal.getTime());
String url = "http://192.168.0.1:1234/test/getData?uid=12&date="
+ dateStr;
/* 建立HttpGet对象 */
HttpGet httpget = new HttpGet(url);
httpget.addHeader("request-key", "test-007"); // 请求访问key
/* 发送请求并等待响应 */
HttpResponse httpResponse = httpClient.execute(httpget);
if (httpResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
/* 读返回数据 */
strResult = EntityUtils.toString(httpResponse.getEntity());
/* json字符串转 list<T> */
JsonParser jsonparer = new JsonParser();
JsonElement je = null;
je = jsonparer.parse(strResult);
Object ob = je.getAsJsonObject().get("data");
Gson gson = new Gson();
List<TestPojo> picInfoList = gson.fromJson(ob.toString(),
new TypeToken<List<TestPojo>>() {
}.getType());
for (TestPojo temp : picInfoList) {
System.out.println(temp.getTime());
}
System.out.println("--strResult:" + strResult);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭连接 ,释放资源
httpClient.getConnectionManager().shutdown();
}
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。