Android http

来源:互联网 发布:mac程序卸载后图标还在 编辑:程序博客网 时间:2024/05/16 08:27
方法一:从应用程序中发起一个HTTP连接。

[html] view plaincopy
  1. ImageView iv = new ImageView(context);  
  2.  iv.setId(12351);  
  3.  String imageUrl = "http://i.pbase.com/o6/92/229792/1/80199697.uAs58yHk.50pxCross_of_the_Knights_Templar_svg.png"; //标准HTTP地址即可  
  4.  try {  
  5.      URL myurl = new URL(imageUrl);  
  6.      HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();  
  7.      conn.setDoInput(true);  
  8.      conn.connect();  
  9.      InputStream is = conn.getInputStream();  
  10.      Bitmap bitmap = BitmapFactory.decodeStream(is);  
  11.      is.close();  
  12.      iv.setImageBitmap(bitmap);  
  13.  } catch (Exception e) {  
  14.      // TODO: handle exception  
  15.  }  
  16.  layout.addView(iv);  


在Manifest.xml中加入uses-permission配置,允许进行网络访问

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="org.studio.crusoe.sample.android" android:versionCode="1"  
  4.     android:versionName="1.0">  
  5.     <uses-permission android:name="android.permission.INTERNET" />  
  6.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  7.         <activity android:name=".ActivityMain" android:label="@string/app_name">  
  8.             <intent-filter>  
  9.                 <action android:name="android.intent.action.MAIN" />  
  10.                 <category android:name="android.intent.category.LAUNCHER" />  
  11.             </intent-filter>  
  12.         </activity>  
  13.   
  14.     </application>  
  15.     <uses-sdk android:minSdkVersion="2" />  
  16.   
  17. </manifest>   

方法二:使用Apache API:

1、使用Map来存储参数

Map<String, String> map = new HashMap<String, String>();
map.put(“name”, “wusheng”);
map.put(“password”, “pwd”);

2、使用DefaultHttpClient创建HttpClient实例

DefaultHttpClient httpClient = new DefaultHttpClient();

3、构建HttpPost

HttpPost post = new HttpPost(“http://wu-sheng.iteye.com”);

4、将由Map存储的参数转化为键值参数

List<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
for (Map.Entry<String, String> entry : map.entrySet()) {
postData.add(new BasicNameValuePair(entry.getKey(),
entry.getValue()));
}

5、使用编码构建Post实体

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
postData, HTTP.UTF_8);

6、设置Post实体

post.setEntity(entity);

7、执行Post方法

HttpResponse response = httpClient.execute(post);

8、获取返回实体

HttpEntity httpEntity = response.getEntity();

9、将H中返回实体转化为输入流

InputStream is = httpEntity.getContent();

10、读取输入流,即返回文本内容

StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = “”;
while((line=br.readLine())!=null){
sb.append(line);
}


例如:Android 通过Http访问Web端的Servlet

[html] view plaincopy
  1. //Http工具类   
  2. import org.apache.http.HttpResponse;   
  3. import org.apache.http.HttpStatus;   
  4. import org.apache.http.client.HttpClient;   
  5. import org.apache.http.client.methods.HttpGet;   
  6. import org.apache.http.impl.client.DefaultHttpClient;   
  7. import org.apache.http.params.BasicHttpParams;   
  8. import org.apache.http.params.HttpConnectionParams;   
  9. import org.apache.http.params.HttpParams;   
  10. import org.apache.http.util.EntityUtils;   
  11.    
  12. public class HttpUtil {   
  13.     public static String getHttpJSON(String url) {   
  14.         HttpGet httpRequest = new HttpGet(url);   
  15.         try {   
  16.             HttpClient httpclient = new DefaultHttpClient();   
  17.             HttpResponse httpResponse = httpclient.execute(httpRequest);   
  18.    
  19.             if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {   
  20.                 String jsonStr = EntityUtils.toString(httpResponse.getEntity(),   
  21.                         "UTF-8");   
  22.                 return jsonStr;   
  23.             }   
  24.         } catch (Exception e) {   
  25.             e.printStackTrace();   
  26.             System.out.println("==============e.printStackTrace() : "   
  27.                     + e.getMessage());   
  28.         }   
  29.         return null;   
  30.     }   
  31.    
  32.     public static int getHttpStatus() {   
  33.         int status = 0;   
  34.         HttpGet httpRequest = new HttpGet(   
  35.                 "http://192.168.0.214/vote/AndroidConnServlet");   
  36.         try {   
  37.             HttpParams httpParameters = new BasicHttpParams();   
  38.             HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);   
  39.             HttpConnectionParams.setSoTimeout(httpParameters, 5000);   
  40.             HttpConnectionParams.setTcpNoDelay(httpParameters, true);   
  41.                
  42.             HttpClient httpclient = new DefaultHttpClient(httpParameters);   
  43.             HttpResponse httpResponse = httpclient.execute(httpRequest);   
  44.    
  45.             status = httpResponse.getStatusLine().getStatusCode();   
  46.         } catch (Exception e) {   
  47.             e.printStackTrace();   
  48.             System.out   
  49.                     .println("==============connection wifi fail,e.printStackTrace() : "   
  50.                             + e.getMessage());   
  51.         }   
  52.         return status;   
  53.     }   
  54.    
  55. }   
  56.    
  57. //调用方法   
  58. public void ensureVote() {   
  59.             String URL = "http://192.168.0.214/vote/VoteServlet";   
  60.             codeText = codeEdit.getText().toString();   
  61.             if (codeText == null || codeText.length() == 0) {   
  62.                 Toast.makeText(VoteActivity.this, "投票失败,请输入投票码.",   
  63.                         Toast.LENGTH_LONG).show();   
  64.                 return;   
  65.             }   
  66.             URL = URL + "?project=" + radioVoteText + "&voteCode=" + codeText   
  67.                     + "&source=Android";   
  68.                
  69.             String httpStatus = "0";   
  70.             httpStatus = HttpUtil.getHttpJSON(URL);   
  71.             if (httpStatus != null && httpStatus.equals("1")) {   
  72.                 new AlertDialog.Builder(VoteActivity.this).setTitle("success")   
  73.                         .setMessage("投票成功,非常感谢.").setNeutralButton("返回",   
  74.                                 new DialogInterface.OnClickListener() {   
  75.                                     public void onClick(DialogInterface dlg,   
  76.                                             int sumthin) {   
  77.                                     }   
  78.                                 }).show();   
  79.             } else if (httpStatus != null && httpStatus.equals("2")) {   
  80.                 new AlertDialog.Builder(VoteActivity.this).setTitle("warn")   
  81.                         .setMessage("投票失败,投票码已经使用.").setNeutralButton("返回",   
  82.                                 new DialogInterface.OnClickListener() {   
  83.                                     public void onClick(DialogInterface dlg,   
  84.                                             int sumthin) {   
  85.                                     }   
  86.                                 }).show();   
  87.             } else if (httpStatus != null && httpStatus.equals("0")) {   
  88.                 new AlertDialog.Builder(VoteActivity.this).setTitle("error")   
  89.                         .setMessage("投票失败,请联系网管.").setNeutralButton("返回",   
  90.                                 new DialogInterface.OnClickListener() {   
  91.                                     public void onClick(DialogInterface dlg,   
  92.                                             int sumthin) {   
  93.                                     }   
  94.                                 }).show();   
  95.             }   
  96.    
  97.         }   
  98.     }