当前位置: 代码迷 >> Android >> android 联接网络
  详细解决方案

android 联接网络

热度:67   发布时间:2016-05-01 15:35:24.0
android 连接网络

http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
package praeda.muzikmekan;
?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
?
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
?
import android.util.Log;
?
public class RestClient {
?
??? private static String convertStreamToString(InputStream is) {
??????? /*
???????? * To convert the InputStream to String we use the BufferedReader.readLine()
???????? * method. We iterate until the BufferedReader return null which means
???????? * there's no more data to read. Each line will appended to a StringBuilder
???????? * and returned as String.
???????? */
??????? 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();
??? }
?
??? /* This is a test function which will connects to a given
???? * rest service and prints it's response to Android Log with
???? * labels "Praeda".
???? */
??? public static void connect(String url)
??? {
?
??????? HttpClient httpclient = new DefaultHttpClient();
?
??????? // Prepare a request object
??????? HttpGet httpget = new HttpGet(url);
?
??????? // Execute the request
??????? HttpResponse response;
??????? try {
??????????? response = httpclient.execute(httpget);
??????????? // Examine the response status
??????????? Log.i("Praeda",response.getStatusLine().toString());
?
??????????? // Get hold of the response entity
??????????? HttpEntity entity = response.getEntity();
??????????? // If the response does not enclose an entity, there is no need
??????????? // to worry about connection release
?
??????????? if (entity != null) {
?
??????????????? // A Simple JSON Response Read
??????????????? InputStream instream = entity.getContent();
??????????????? String result= convertStreamToString(instream);
??????????????? Log.i("Praeda",result);
?
??????????????? // A Simple JSONObject Creation
??????????????? JSONObject json=new JSONObject(result);
??????????????? Log.i("Praeda","<jsonobject>\n"+json.toString()+"\n</jsonobject>");
?
??????????????? // A Simple JSONObject Parsing
??????????????? JSONArray nameArray=json.names();
??????????????? JSONArray valArray=json.toJSONArray(nameArray);
??????????????? for(int i=0;i<valArray.length();i++)
??????????????? {
??????????????????? Log.i("Praeda","<jsonname"+i+">\n"+nameArray.getString(i)+"\n</jsonname"+i+">\n"
??????????????????????????? +"<jsonvalue"+i+">\n"+valArray.getString(i)+"\n</jsonvalue"+i+">");
??????????????? }
?
??????????????? // A Simple JSONObject Value Pushing
??????????????? json.put("sample key", "sample value");
??????????????? Log.i("Praeda","<jsonobject>\n"+json.toString()+"\n</jsonobject>");
?
??????????????? // Closing the input stream will trigger connection release
??????????????? instream.close();
??????????? }
?
?
??????? } catch (ClientProtocolException e) {
??????????? // TODO Auto-generated catch block
??????????? e.printStackTrace();
??????? } catch (IOException e) {
??????????? // TODO Auto-generated catch block
??????????? e.printStackTrace();
??????? } catch (JSONException e) {
??????????? // TODO Auto-generated catch block
??????????? e.printStackTrace();
??????? }
??? }
?
}

2.如果你要连接两次那么一定记得加上:
System.setProperty("http.keepAlive", "false")
3.测试代码
public static String get(String url) throws IOException {

? ? ? ?
ByteArrayOutputStream os = new ByteArrayOutputStream();
? ?
URLConnection conn=null;
? ? ? ?
byte[] buf = new byte[4096];

? ? ? ?
try {
? ? ? ? ? ? ? ? URL a
= new URL(url);
? ? ? ? ? ? ? ? conn
= a.openConnection();
? ? ? ? ? ? ? ?
InputStream is = conn.getInputStream();
? ? ? ? ? ? ? ?
int ret = 0;
? ? ? ? ? ? ? ?
while ((ret = is.read(buf)) > 0) {
? ? ? ? ? ? ? ? ? ? ? ? os
.write(buf, 0, ret);
? ? ? ? ? ? ? ?
}
? ? ? ? ? ? ? ?
// close the inputstream
? ? ? ? ? ? ? ?
is.close();
? ? ? ? ? ? ? ?
return new String(os.toByteArray());
? ? ? ?
} catch (IOException e) {
? ? ? ? ? ? ? ?
try {
? ? ? ? ? ? ? ? ? ? ? ?
int respCode = ((HttpURLConnection)conn).getResponseCode();
? ? ? ? ? ? ? ? ? ? ? ?
InputStream es = ((HttpURLConnection)conn).getErrorStream();
? ? ? ? ? ? ? ? ? ? ? ?
int ret = 0;
? ? ? ? ? ? ? ? ? ? ? ?
// read the response body
? ? ? ? ? ? ? ? ? ? ? ?
while ((ret = es.read(buf)) > 0) {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? os
.write(buf, 0, ret);
? ? ? ? ? ? ? ? ? ? ? ?
}
? ? ? ? ? ? ? ? ? ? ? ?
// close the errorstream
? ? ? ? ? ? ? ? ? ? ? ? es
.close();
? ? ? ? ? ? ? ? ? ? ? ?
return "Error response " + respCode + ": " +
? ? ? ? ? ? ? ? ? ? ? ? ? ?
new String(os.toByteArray());
? ? ? ? ? ? ? ?
} catch(IOException ex) {
? ? ? ? ? ? ? ? ? ? ? ?
throw ex;
? ? ? ? ? ? ? ?
}
? ? ? ?
}
}

?

??????? try {

? ? ? ? ? ? ? ? URL url
= new URL("http://"+params[0]);

? ? ? ?
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
? ? ? ? urlc
.setRequestProperty("User-Agent", "Android Application:"+Z.APP_VERSION);
? ? ? ? urlc
.setRequestProperty("Connection", "close");
? ? ? ? urlc
.setConnectTimeout(1000 * 30); // mTimeout is in seconds
? ? ? ? ? ? ? ? urlc
.connect();
? ? ? ?
if (urlc.getResponseCode() == 200) {
? ? ? ? ? ?
Main.Log("getResponseCode == 200");
? ? ? ? ? ? ? ?
return new Boolean(true);
? ? ? ?
}
? ? ? ?
} catch (MalformedURLException e1) {
? ? ? ? ? ? ? ?
// TODO Auto-generated catch block
? ? ? ? ? ? ? ? e1
.printStackTrace();
? ?
} catch (IOException e) {
? ? ? ? ? ? ? ?
// TODO Auto-generated catch block
? ? ? ? ? ? ? ? e
.printStackTrace();
? ? ? ?
}

?常用方法有

import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams;      try {         int TIMEOUT_MILLISEC = 10000;  // = 10 seconds         HttpParams httpParams = new BasicHttpParams();         HttpConnectionParams.setConnectionTimeout(httpParams,                                                   TIMEOUT_MILLISEC);         HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);         HttpClient client = new DefaultHttpClient(httpParams);          HttpPost request = new HttpPost(serverUrl);         request.setEntity(new ByteArrayEntity(             postMessage.toString().getBytes("UTF8")));          HttpResponse response = client.execute(request);     } catch (Exception e) {         ....     } 

?

  相关解决方案