HttpClient接口Post方式

import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
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.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class mainActivity extends Activity {
    TextView tv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) findViewById(R.id.tv1);
        // HttpPost连接对象
        HttpPost httpRequset = new HttpPost("http://10.0.2.2:8080/dem/");
        // 使用NameValuePair来保存要传递的Post参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // 添加要传递的参数
        params.add(new BasicNameValuePair("par", "asdf"));
        try {
            // 设置字符集
            HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");
            // 请求httpRequset
            httpRequset.setEntity(httpentity);
            // 取得HttpClient
            HttpClient httpClient = new DefaultHttpClient();
            // 取得HttpResponse
            HttpResponse httpResponse = httpClient.execute(httpRequset);
            if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String strResult = EntityUtils.toString(httpResponse
                        .getEntity());
                tv.setText(strResult);
            }
            else {
                tv.setText("请求错误");
            }
        }
        catch(Exception e) {
            Log.e("", e.getMessage());
        }
    }
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

你可能感兴趣的:(exception,String,Class)