PHP
·
发表于 5年以前
·
阅读量:8312
一般服务端提从的API接口,都为字符串,客户端访问获取后,将取转换为Json对象,对于此类操作,本质是访问HTTP,得到字符串形式的body。
示例代码如下所示:
public class HttpHelper {
public interface HttpRequestCallback{
void onGetContent(String text);
}
public static void httpGet(final String url, final HttpRequestCallback callback){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection=null;
try{
URL urlObject = new URL(url);
connection = (HttpURLConnection)urlObject.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
BufferedReader bufr = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line = null;
while((line=bufr.readLine()) != null){
response.append(line);
}
if(callback != null){
callback.onGetContent(response.toString());
}
}catch(Exception e){
e.printStackTrace();
}finally {
closeConnection(connection);
}
}
}).start();
}
public static void closeConnection(HttpURLConnection closeable){
if(closeable != null){
try{
closeable.disconnect();
}catch (Exception ex){
ex.printStackTrace();
}
}
}
}