* 創建HttpClient實例 , 並返回請求信息。
* @param url
* @return
* @throws Exception
*/
public String createHttpClient(String url) throws Exception{
// 創建HttpClient實例
HttpClient httpclient = new DefaultHttpClient();
// 創建Get方法實例
HttpGet httpgets = new HttpGet(url);
HttpResponse response = httpclient.execute(httpgets);
HttpEntity entity = response.getEntity();
String str = "";
if (entity != null) {
InputStream instreams = entity.getContent();
str = convertStreamToString(instreams);
System.out.println(str);
httpgets.abort();
}
return str;
}
/**
* 讀取流
* @param is
* @return
*/
public String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
@Test
public void testSaveCusIdea(){
String url = "";
try {
// URLEncoder.encode("參數內容","編碼格式") 如果不把參數轉換編碼,瀏覽器就無法讀取。
// java.lang.IllegalArgumentException at java.net.URI.create(URI.java:842) 錯誤信息
url = "http://www.xuanque.net/idea/saveCusIdea?param="+URLEncoder.encode("{idea:'意見內容',cid:'',email:'[email protected]'}","UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
String resStr = createHttpClient(url);
System.out.println(resStr);
} catch (Exception e) {
e.printStackTrace();
}
}