1. 程式人生 > >httpClient傳送key_value、json引數及檔案

httpClient傳送key_value、json引數及檔案

本文使用的是httpClient實現傳送key_value引數、json引數,上傳單個檔案,上傳多個檔案的功能,是目前市面上很多網路請求封裝工具類的實現原理。

PostActivity:

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import
org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.ContentBody; import org.apache.http.entity.mime.content.FileBody; import
org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; /** * @author CSDN_LQR * @工程 7ZipDemo * @包名 com.lqr.zipdemo * @TODO
使用httpClient實現發再key_value引數、json引數、上傳多個檔案 */
public class PostActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO super.onCreate(savedInstanceState); setContentView(R.layout.activity_post); /* =============== post key_value =============== */ findViewById(R.id.btnKeyValue).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { HashMap<String, String> params = new HashMap<String, String>(); params.put("name", "SCDN_LQR"); // 傳送key_value形式的post請求 postKeyValue(params); } }); /* =============== post key_jsonString=============== */ findViewById(R.id.btnJsonString).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { String jsonString = "{\"name\":\"CSDN_LQR\"}"; postJsonString(jsonString); } }); /* =============== post key_File 單張圖片=============== */ findViewById(R.id.btnSingleFile).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { File file = new File("c:/a.txt"); postSingleFile(file); } }); /* =============== post key_File 多張圖片=============== */ findViewById(R.id.btnMultFile).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { Map<String, File> fileMap = new HashMap<String, File>(); File actimgFile = null; File listimgFile = null; fileMap.put("actimg", actimgFile); fileMap.put("listimg", listimgFile); postMultFile(fileMap); } }); } /** * 傳送多個檔案,需要httpmime.jar的支援 * * @param fileMap */ private void postMultFile(final Map<String, File> fileMap) { new Thread(new Runnable() { @Override public void run() { try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost("http://httpbin.org/post"); // 提交檔案型別的引數 MultipartEntity entity = new MultipartEntity(); for (Map.Entry<String, File> info : fileMap.entrySet()) { File file = info.getValue(); String key = info.getKey(); ContentBody contentBody = new FileBody(file); entity.addPart(key, contentBody); } post.setEntity(entity); HttpResponse response = httpClient.execute(post); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity resEntity = response.getEntity(); String result = EntityUtils.toString(resEntity); System.out.println("result:" + result); } } catch (Exception e) { e.printStackTrace(); } } }).start(); } /** * 傳送單個檔案,需要httpmime.jar的支援 * * @param file */ private void postSingleFile(final File file) { new Thread(new Runnable() { @Override public void run() { try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost("http://httpbin.org/post"); // 提交檔案型別的引數 MultipartEntity entity = new MultipartEntity(); ContentBody contentBody = new FileBody(file); entity.addPart("actimg", contentBody); post.setEntity(entity); HttpResponse response = httpClient.execute(post); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity resEntity = response.getEntity(); String result = EntityUtils.toString(resEntity); System.out.println("result:" + result); } } catch (Exception e) { e.printStackTrace(); } } }).start(); } /** * 傳送json形式的post請求 * * @param jsonString */ private void postJsonString(final String jsonString) { new Thread() { public void run() { try { DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://httpbin.org/post"); // 提交表單型別的引數 post.setEntity(new StringEntity(jsonString)); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); System.out.println(EntityUtils.toString(entity)); } } catch (Exception e) { // TODO e.printStackTrace(); } }; }.start(); } /** * 傳送key_value形式的post請求 * * @param paramsMap */ private void postKeyValue(final Map<String, String> paramsMap) { new Thread() { public void run() { try { DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://httpbin.org/post"); List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>(); for (Entry<String, String> entry : paramsMap.entrySet()) { BasicNameValuePair basicNameValuePair = new BasicNameValuePair( entry.getKey(), entry.getValue()); parameters.add(basicNameValuePair); } UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity( parameters); // 提交表單型別的引數 post.setEntity(reqEntity); HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity resEntity = response.getEntity(); System.out.println(EntityUtils.toString(resEntity)); } } catch (Exception e) { // TODO e.printStackTrace(); } }; }.start(); } }

activity_post.xml:

<LinearLayout 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"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/btnKeyValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="post_key_value" />


    <Button
        android:id="@+id/btnJsonString"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="post_jsonStirng" />

    <Button
        android:id="@+id/btnSingleFile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="post_singleFile" />

    <Button
        android:id="@+id/btnMultFile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="post_multFile" />

</LinearLayout>