導航:首頁 > 操作系統 > androidurlstring

androidurlstring

發布時間:2022-07-04 05:30:43

android中怎麼把String進行url編碼

java中一樣使用的吧URLEncode.encode("string","utf8");

Ⅱ 如何解析從Android的一個字元串的URL

需要根據URL地址獲取圖片載入到圖中Anroid機器人所在的位置,這是運行前的效果
首先需根據URL地址獲取圖片,如下所示,urladdr即為圖片地址,返回Drawable對象:
//download image from network using @urladdress
private Drawable loadImageFromNetwork(String urladdr) {
// TODO Auto-generated method stub
Drawable drawable = null;
try{
//judge if has picture locate or not according to filename
drawable = Drawable.createFromStream(new URL(urladdr).openStream(), "image.jpg");
}catch(IOException e){
Log.d("test",e.getMessage());
}
if(drawable == null){
Log.d("test","null drawable");
}else
Log.d("test","not null drawable");
}
return drawable;
}
獲取到圖片後,需要更新主線程UI資源,考慮到時間以及界面反應延遲等,所以採用線程加以處理,如下圖所示:
// image
new Thread(new Runnable(){
Drawable drawable = loadImageFromNetwork(urladdress);
@Override
public void run(){
//post() is quite important,update pictures in UI main thread
image.post(new Runnable(){
@Override
public void run(){
//TODO Auto-generated method stub
image.setImageDrawable(drawable);
}
});
}
//download image from network using @urladdress
private Drawable loadImageFromNetwork(String urladdr) {
//... 略(如 1 中所示)
}
}).start(); //線程啟動

4.說明:在上述示例代碼中,image是ImageView類的一個對象,也就是APP中的一個顯示圖像組件,利用獲取到的圖片drawable去更新image,

Ⅲ android根據url獲取網路圖片報錯

這個看著是https協議的URL,用普通的http請求就報錯了,我這里只有請求https到流的代碼,給你先看看,把流再轉成文件 就可以了


@SuppressLint("ParserError")
(StringdownUrl,StringpostStr)throwsIOException{
Stringres="";

HttpsURLConnection.setDefaultHostnameVerifier(newNullHostNameVerifier());
SSLContextcontext=null;
try{
context=SSLContext.getInstance("TLS");
}catch(NoSuchAlgorithmExceptione1){
//TODOAuto-generatedcatchblock
e1.printStackTrace();
}

try{
context.init(null,newX509TrustManager[]{newmyX509TrustManager()},newSecureRandom());
}catch(KeyManagementExceptione1){
//TODOAuto-generatedcatchblock
e1.printStackTrace();
}
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());

URLdUrl=newURL(downUrl);
HttpsURLConnectiondConn=(HttpsURLConnection)dUrl.openConnection();

dConn.setDoInput(true);
if(postStr!=""){
dConn.setDoOutput(true);
dConn.setRequestMethod("POST");
}

dConn.connect();

if(postStr!=""){
try{
BufferedWriterout=newBufferedWriter(newOutputStreamWriter(
dConn.getOutputStream()));
out.write(postStr);
out.flush();

}catch(Exceptione){
StringerrMsg=e.getMessage();
if(null!=errMsg){
Toasttoast=Toast.makeText(null,errMsg,Toast.LENGTH_LONG);
toast.show();
}

e.printStackTrace();
}

}


BufferedInputStreamin=newBufferedInputStream(dConn.getInputStream());

returnin;
}


{
@Override
publicbooleanverify(Stringhostname,SSLSessionsession){
//Log.i("RestUtilImpl","Approvingcertificatefor"+hostname);
returntrue;
}
}

{
@Override
publicX509Certificate[]getAcceptedIssuers(){
returnnull;
}

@Override
publicvoidcheckClientTrusted(X509Certificate[]chain,StringauthType)
throwsCertificateException{
//TODOAuto-generatedmethodstub
}

@Override
publicvoidcheckServerTrusted(X509Certificate[]chain,StringauthType)
throwsCertificateException{
//TODOAuto-generatedmethodstub
}
}

Ⅳ 如何修改android系統設置

Ⅳ android 從json中解析出了所需圖片的url(String)。

imageloader載入網路圖片或者volley的metworkimageview載入網路圖片

Ⅵ android 判斷url是否有效

//檢查網路連接狀態,Monitor network connections (Wi-Vi, GPRS, UMTS, etc.)
public static boolean checkNetWorkStatus(Context context){
boolean result;
ConnectivityManager cm=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = cm.getActiveNetworkInfo();
if ( netinfo !=null && netinfo.isConnected() ) {
result=true;
Log.i(TAG, "The net was connected" );
}else{
result=false;
Log.i(TAG, "The net was bad!");
}
return result;
}
public static boolean checkURL(String url){
boolean value=false;
try {
HttpURLConnection conn=(HttpURLConnection)new URL(url).openConnection();
int code=conn.getResponseCode();
System.out.println(">>>>>>>>>>>>>>>> "+code+" <<<<<<<<<<<<<<<<<<");
if(code!=200){
value=false;
}else{
value=true;
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
}

Ⅶ android 如何獲得網路文件大小

public long getFileSize(String urlString) throws IOException,Exception{
long lenght = 0;
String url = UrlEncode(urlString, "UTF-8");
//URL mUrl = new URL(urlString);
URL mUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();
conn.setConnectTimeout(5*1000);
conn.setRequestMethod("GET");
conn .setRequestProperty("Accept-Encoding", "identity");
conn.setRequestProperty("Referer", url);
//conn.setRequestProperty("Referer", urlString);
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.connect();

int responseCode = conn.getResponseCode();
// 判斷請求是否成功處理
if (responseCode == HttpStatus.SC_OK) {
lenght = conn.getContentLength();
}

return lenght;
}

Ⅷ 如何在Android開發中用HttpClient連接網路數據

HttpClient網路訪問

一、HttpClient網路訪問:
(一)、簡介:
1、Apache組織提供了HttpClient項目,可以實現網路訪問。在Android中,成功集成了HttpClient,所以在Android中可以直接使用HttpClient訪問網路。

2、與HttpURLConnection相比,HttpClient將前者中的輸入、輸出流操作,統一封裝成HttpGet、HttpPost、HttpRequest類。

HttpClient:網路連接對象;
HttpGet:代表發送GET請求;
HttpPost:代表發送POST請求;
HttpResponse:代表處理伺服器響應的對象。
HttpEntity對象:該對象中包含了伺服器所有的返回內容。
3、使用步驟:(六部曲)【重點】
創建HttpClient對象:通過實例化DefaultHttpClient獲得;
創建HttpGet或HttpPost對象:通過實例化 HttpGet或HttpPost 獲得,而構造方法的參數是urlstring(即需要訪問的網路url地址)。也可以通過調用setParams()方法來添加請求參數;
調用HttpClient對象的execute()方法,參數是剛才創建的 HttpGet或HttpPost對象 ,返回值是HttpResponse對象;
通過response對象中的getStatusLine()方法和getStatusCode()方法獲取伺服器響應狀態是否是200。
調用 HttpResponse對象的getEntity()方法,返回HttpEntity對象。而該對象中包含了伺服器所有的返回內容。
藉助EntityUtils的toString()方法或toByteArray()對 HttpEntity對象進行處理,也可以通過IO流對 HttpEntity對象進行操作。

(二)、封裝HttpClientHelper工具類:

public class HttpClientHelper {
public static HttpClient checkNetwork(String url) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(request);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
return httpClient;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

/**
* 作用:實現網路訪問文件,將獲取到數據儲存在文件流中
*
* @param url
* :訪問網路的url地址
* @return inputstream
*/
public static InputStream loadFileFromURL(String url) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet requestGet = new HttpGet(url);
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(requestGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResponse.getEntity();
return entity.getContent();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 作用:實現網路訪問文件,將獲取到的數據存在位元組數組中
*
* @param url
* :訪問網路的url地址
* @return byte[]
*/
public static byte[] loadByteFromURL(String url) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet requestGet = new HttpGet(url);
try {
HttpResponse httpResponse = httpClient.execute(requestGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toByteArray(httpEntity);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("====>" + e.toString());
}
return null;
}

/**
* 作用:實現網路訪問文件,返回字元串
*
* @param url
* :訪問網路的url地址
* @return String
*/
public static String loadTextFromURL(String url) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet requestGet = new HttpGet(url);
try {
HttpResponse httpResponse = httpClient.execute(requestGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toString(httpEntity, "utf-8");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 作用:實現網路訪問文件,先給伺服器通過「GET」方式提交數據,再返回相應的數據
*
* @param url
* :訪問網路的url地址
* @param params
* String url:訪問url時,需要傳遞給伺服器的參數。
* 第二個參數格式為:username=wangxiangjun&password=123456
* @return byte[]
*/
public static byte[] doGetSubmit(String url, String params) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet requestGet = new HttpGet(url + "?" + params);
try {
HttpResponse httpResponse = httpClient.execute(requestGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toByteArray(httpEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 作用:實現網路訪問文件,先給伺服器通過「POST」方式提交數據,再返回相應的數據
*
* @param url
* :訪問網路的url地址
* @param params
* String url:訪問url時,需要傳遞給伺服器的參數。 第二個參數為:List<NameValuePair>
* @return byte[]
*/
public static byte[] doPostSubmit(String url, List<NameValuePair> params) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost requestPost = new HttpPost(url);
try {
requestPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
HttpResponse httpResponse = httpClient.execute(requestPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toByteArray(httpEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 作用:實現網路訪問文件,先給伺服器通過「POST」方式提交數據,再返回相應的數據
*
* @param url
* :訪問網路的url地址
* @param params
* String url:訪問url時,需要傳遞給伺服器的參數。 Map<String , Object>
* @return byte[]
*/
public static byte[] doPostSubmit(String url, Map<String, Object> params) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost requestPost = new HttpPost(url);

List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
try {
if (params != null) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
BasicNameValuePair nameValuePair = new BasicNameValuePair(
key, value);
parameters.add(nameValuePair);
}
}
requestPost
.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));
HttpResponse httpResponse = httpClient.execute(requestPost);

if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toByteArray(httpEntity);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

Ⅸ 在Android的URL中怎麼沒得openConnection方法

好像是包的問題、我的一個demo:
package com.chapter8;

import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MyNetWeb extends CloseMenuActivity {
private TextView tvname;
private TextView tvpass;
private EditText evname;
private EditText evpass;
private Button btsubmit;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.netweb);

tvname = (TextView)findViewById(R.id.tvname);
tvpass = (TextView)findViewById(R.id.tvpass);
evname = (EditText)findViewById(R.id.etname);
evpass = (EditText)findViewById(R.id.etpass);
btsubmit = (Button)findViewById(R.id.btsubmit);

btsubmit.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name = evname.getText().toString().trim();
String password = evpass.getText().toString().trim();

String urlString = "";
try {
URL url = new URL(urlString);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.connect();
http.setRequestMethod("POST");
OutputStreamWriter osw = new OutputStreamWriter(http.getOutputStream());
osw.write("");
osw.flush();
osw.close();
tvname.setText(http.getInputStream().read());
http.disconnect();
tvpass.setText("ok");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
tvpass.setText(e.getMessage());
}

}
});
}
}

Ⅹ 如何在Android中實現一個簡單連接網路的應用程序

注意:要執行這節課中描述的網路操作,你應用程序的manifest文件中必須包含以下許可權:1 2<uses-permissionandroid:name="android.permission.INTERNET"/><uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>選擇一個HTTP客戶端 Choose an HTTP Client大多數網路連接的Android應用使用HTTP發送和接受數據,Android包括兩個HTTP客戶端:HttpURLConnection和Apache HttpClient,它們支持HTTPS,流上傳和下載,
可配置的超時,IPv6以及連接池,在android系統版本為「姜餅」(android2.3)或者更高版本的應用程序中,推薦使用HttpURLConnection,更多關於這個主題的討論,請查看博客Android HTTP 客戶端檢查網路連接 Check the Network Connection在你的應用試圖連接到網路時,應該先檢查網路連接是否可用,可以用getActiveNetworkInfo()和isConnected()方法執行檢查。記住,設備(手機等設備)可能不在網路連接的范圍內,或者用戶禁用了Wi-Fi或者移動數據通道。更多關於此主題的討論,請參看課程管理網路使用
1 2 3 4 5 6 7 8 9 10 11 12publicvoidmyClickHandler(Viewview){...ConnectivityManagerconnMgr=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfonetworkInfo=connMgr.getActiveNetworkInfo();if(networkInfo!=null&&networkInfo.isConnected()){// 獲取數據}else{// 顯示錯誤}...}在獨立線程中執行網路連接 Perform Network Operations on a Separate Thread網路操作涉及不可預知的延遲,為了防止不良的用戶體驗,通常的做法是從UI中獨立出線程去執行網路連接操作。AsyncTask類提供了最簡單的從UI線程中獨立出一個新任務的方式。
更多關於此主題的討論,請參看博客多線程性能在下面的代碼片段中,myClickHandler()方法執行了new DownloadWebpageTask().execute(stringUrl).DownloadWebpageTask類是AsyncTask的子類,DownloadWebpageTask實現了下面AsyncTask的方法:
doInbackground()會執行downloadUrl()方法,downlaodUrl()方法將網頁的URL地址作為參數,並獲取和處理網頁的內容,當它處理完這些操作,將會返回一個結果字元串。
onPostExecute()接受返回字元串並顯示在UI上。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 {privatestaticfinalStringDEBUG_TAG="HttpExample";privateEditTexturlText;privateTextViewtextView;@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);urlText=(EditText)findViewById(R.id.myUrl);textView=(TextView)findViewById(R.id.myText);}// 當用戶點擊按鈕,調用AsyncTask// 在試圖獲取URL時,確保有一個網路連接publicvoidmyClickHandler(Viewview){// 從UI的text欄位中得到URLStringstringUrl=urlText.getText().toString();ConnectivityManagerconnMgr=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfonetworkInfo=connMgr.getActiveNetworkInfo();if(networkInfo!=null&&networkInfo.isConnected()){newDownloadWebpageText().execute(stringUrl);}else{textView.setText("No network connection available.");}}// 使用AsyncTask創建一個獨立於主UI線程之外的任務. 並使用URL字元串創建一個HttpUrlConnection對象。 // 一旦連接建立,AsyncTask則將網頁內容作為一個InputStream對象進行下載。// 最終,InputStream對象會被轉換為一個字元串對象,並被AsyncTask的onPostExecute方法顯示在UI上。{@(String...urls){// 參數來自execute(),調用params[0]得到URLtry{returndownloadUrl(urls[0]);}catch(IOExceptione){return"無法獲取網頁,URL可能無效!Unable to retrieve web page. URL may be invalid.";}}// onPostExecute顯示AsyncTask結果.@(Stringresult){textView.setText(result);}}...}該片段事件順序如下:1.當用戶點擊執行myClickHander()方法的按鈕時,應用會將指定的URL傳遞給AsyncTask的子類DownloadWebpageTask。2.AsyncTask的方法doInBackground()調用downloadUrl()。3.downloadUrl()接收到作為字元串參數傳遞過來的URL,並用它創建一個URL對象。4.使用URL對象創建HttpURLConnection對象。5.一旦創建完HttpURLConnection對象,該對象將會以InputStream對象方式獲取網頁內容。6.InputStream再通過readIt()方法將流轉換為字元。7.最後,AsyncTask的onPostExecute方法將字元顯示在主activity的UI。連接並下載數據 Connect and Download Data在你執行網路事務的線程中,你可以使用HttpURLConnection執行GET方法下載數據,在你調用了connect()方法後,你可以通過調用getInputStream()方法得到數據的InputStream對象。
在下面的代碼片段中,doInBackground()方法調用了downloadUrl()方法。downloadUrl方法接收給過來的URL,並使用它通過HttpURLConnection對象連接到網路。一旦連接成功,應用將使用getInputStream()方法獲得InputStream對象數據。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31// 給一個URL,建立HttpUrlConnection對象並作為流對象(InputStream)獲取網頁數據,最後返回一個字元串。privateStringdownloadUrl(Stringmyurl)throwsIOException{InputStreamis=null;// 先顯示獲取到的前500個位元組// 網頁內容intlen=500;try{URLurl=newURL(myurl);HttpURLConnectionconn=(HttpURLConnection)url.openConnection();conn.setReadTimeout(10000/*milliseconds*/);conn.setConnectTimeout(15000/*milliseconds*/);conn.setRequestMethod("GET");conn.setDoInput(true);// 開始查詢conn.connect();intresponse=conn.getResponseCode();Log.d(DEBUG_TAG,"The response is: "+response);is=conn.getInputStream();// 將InputStream轉化為stringStringcontentAsString=readIt(is,len);returncontentAsString;// 確保當app用完InputStream對象後關閉它。}finally{if(is!=null){is.close();}}}注意:getResponseCode()方法返回的是連接狀態碼,它是獲取更多關於連接信息的有效方式。狀態碼200表示連接成功。

閱讀全文

與androidurlstring相關的資料

熱點內容
堵車如何緩解壓力 瀏覽:15
喜鵲快貸app怎麼了 瀏覽:263
海龜編輯器積木編程怎麼安裝 瀏覽:185
程序員理發店生意怎麼樣 瀏覽:603
程序員羅技 瀏覽:180
軟考初級程序員課程2021下載 瀏覽:491
杭州程序員奶奶 瀏覽:880
不聽命令造成錯誤 瀏覽:981
kool系統源碼 瀏覽:610
流氓app在哪裡看 瀏覽:98
域名購買了怎麼指向伺服器 瀏覽:121
安卓手機如何讓照片顏色反轉 瀏覽:859
怎麼下載卓睿安手機版 瀏覽:514
h3crange命令 瀏覽:468
php前景和python 瀏覽:338
php壓縮圖片內存大小 瀏覽:495
在哪裡可以查看雲伺服器的信息 瀏覽:70
python讀取非txt文件 瀏覽:799
艾莫迅用什麼編程軟體好 瀏覽:227
android文件存儲讀取 瀏覽:214