慕課網的智能機器人的那個項目視頻中學到的。
寫了一個工具類(HttpUtils),可以寫一個單元測試去測試其類的功能是否正確,而不必等佈局文件寫好再去測試。
貼代碼一:HttpUtils工具類
public class HttpUtils {
private static final String URL="http://www.tuling123.com/openapi/api";
private static final String API_KEY="950e94cd5cf0a9de9a66d68a6c240502";
public static String doGet(String msg){
String result ="";
String url =setParams(msg);
Log.i("TAG","zzj--url地址-->>"+url);
InputStream is=null;
ByteArrayOutputStream baos=null;
try {
java.net.URL urlNet = new java.net.URL(url);
HttpURLConnection conn =(HttpURLConnection)urlNet.openConnection();
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
is =conn.getInputStream();
int len=-1;
byte[]buf = new byte[128];
baos =new ByteArrayOutputStream();
while((len=is.read(buf))!=-1){
baos.write(buf,0,len);
}
result = new String(baos.toByteArray());
baos.flush();
Log.i("TAG","-HTTP-1>>"+result);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(baos!=null){
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Log.i("TAG","-HTTP->2>"+result);
return result;
}
private static String setParams(String msg) {
String url="";
try {
url=URL+"?key="+API_KEY+"&info="+URLEncoder.encode(msg,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return url;
}
}
貼代碼二: 要在AndroidManifest.xml中寫兩個標籤<uses-library /> <instrumentation />
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.robot"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<uses-library android:name="android.test.runner"/>
<activity
android:name="com.example.robot.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<instrumentation android:targetPackage="com.example.robot"
android:label="this is a test"
android:name="android.test.InstrumentationTestRunner"></instrumentation>
</manifest>
public class TestHttpUtils extends AndroidTestCase {
public void testSendInfo(){
String res =HttpUtils.doGet("給我講個笑話");
Log.i("TAG","z-笑話->>"+res);
res = HttpUtils.doGet("給我講個鬼故事");
Log.i("TAG","z-故事->>"+res);
}
}
使用方法: 鼠標選中testSendInfo()方法的位置,右鍵 run as -> Android jUnit Test