RxJava + httpURLConnectionde 的簡單測試demo,可以拿來處理一般的android訪問網路的執行緒問題
//主要程式碼
Observable.create(new Observable.OnSubscribe<String>() {
@Overridepublic void call(Subscriber<? super String> subscriber) {
String bitmap =HttpUtil.sendHttpRequest("","http://192.168.8.161:1111/api/Test/GetMatList7");
try{ Thread.sleep(3000);}catch(Exception e){}
subscriber.onNext(bitmap);
subscriber.onCompleted();
Log.e(" call ---> ", "執行在 " + Thread.currentThread().getName() + " 執行緒");
}
}).subscribeOn(Schedulers.newThread()) // 指定subscribe()發生在IO執行緒
.observeOn(AndroidSchedulers.mainThread()) // 指定Subscriber的回調發生在UI執行緒
.subscribe(new Subscriber<String>() {
@Override
public void onStart() {
super.onStart();
p.show();
}
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
p.dismiss();
Log.e(" call ---> ", "執行在 " + Thread.currentThread().getName() + " 執行緒");
// System.out.println(s);
Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT).show();
}
});
//util中的方法的寫法
public static String sendHttpRequest(final String str,final String address){
//通過 HttpURLConnection連線伺服器第一個引數為傳入的引數,第二個位url地址
HttpURLConnection conn=null;
try{
URL url = new URL(address);
conn=(HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(8000);
conn.setReadTimeout(8000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(str);
out.flush();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while((line=reader.readLine())!=null){
response.append(line);
}
System.out.println(response.toString());
return response.toString();
}catch (Exception e){
System.out.println("異常是:"+e.getMessage());
e.getMessage();
}finally {
if(conn!=null){
conn.disconnect();
}
}
return "仆街啦";
}