Android為HttpClient設定認證(使用者名稱和密碼)

來源:互聯網
上載者:User

MainActivity如下:

package cc.testhtmlcontent;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.NameValuePair;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.CredentialsProvider;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.BasicCredentialsProvider;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.params.HttpConnectionParams;import org.apache.http.protocol.HTTP;import android.os.Bundle;import android.app.Activity;/** * Demo描述: * 1 為HttpClient設定認證(CredentialsProvider 認證提供者) * 2 然後擷取HTML中的內容 *  */public class MainActivity extends Activity {private final String USERNAME="your username";private final String PASSWORD="your password";    private final String URL="your url";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);getHTMLContent();}private void getHTMLContent() {try {new Thread(new Runnable() {public void run() {ArrayList<NameValuePair> nameValuePairArrayList = new ArrayList<NameValuePair>();String HTMLContent = getHTMLContentByPost(nameValuePairArrayList, URL,false);System.out.println("HTMLContent=" + HTMLContent);}}).start();} catch (Exception e) {}}public  String getHTMLContentByPost(ArrayList<NameValuePair> nameValuePairArrayList,String url, boolean hasCredential) {InputStream inputStream = null;String line = "";String htmlContentString = "";HttpPost httpPost = new HttpPost(url);DefaultHttpClient httpClient = new DefaultHttpClient();//當需要認證的時候//對HttpClient進行如下設定:if (hasCredential) {AuthScope authScope=new AuthScope(AuthScope.ANY_HOST,AuthScope.ANY_PORT);UsernamePasswordCredentials usernamePasswordCredentials=new UsernamePasswordCredentials(USERNAME, PASSWORD);CredentialsProvider credentialsProvider = new BasicCredentialsProvider();credentialsProvider.setCredentials(authScope, usernamePasswordCredentials);httpClient.setCredentialsProvider(credentialsProvider);}try {HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 8000);HttpConnectionParams.setSoTimeout(httpClient.getParams(), 9000);HttpConnectionParams.setTcpNoDelay(httpClient.getParams(), true);httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairArrayList, HTTP.UTF_8));HttpResponse httpResponse = httpClient.execute(httpPost);if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {HttpEntity httpEntity = httpResponse.getEntity();inputStream = httpEntity.getContent();InputStreamReader inputStreamReader=new InputStreamReader(inputStream, HTTP.UTF_8);BufferedReader bufferedReader = new BufferedReader(inputStreamReader);while ((line = bufferedReader.readLine()) != null) {htmlContentString += line;}}} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}clientShutdown(httpClient);return htmlContentString;}//關閉client連結public static void clientShutdown(HttpClient client) {client.getConnectionManager().shutdown();}}


 

main.xml如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"     >    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="擷取HTML的內容"        android:layout_centerInParent="true"     /></RelativeLayout>


 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.