android中的HTTP POST请求

时间:2014-04-23 08:44:11

标签: android http-post

我需要将http post请求发送到服务器(我想发送一个字符串)并在android应用程序中作为JSON对象输出。我怎么能用异步类来做。

4 个答案:

答案 0 :(得分:0)

尝试以下代码: -

class RequestAsyncTask extends AsyncTask<String, Integer, String>
{

    @Override
    protected void onPreExecute()
    {

        {
            dialog = new ProgressDialog(Activity.this);
            dialog.setIndeterminate(true);
            dialog.setCancelable(false);
            dialog.show();
        }
    }

    @Override
    protected String doInBackground(String... params)
    {
        String status = "";
        try
        {
            HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 60000);
    HttpResponse response;

    try
    {

        HttpPost post = new HttpPost("url name");//

        System.out.println("jsonObject       " + jsonObject.toString());
        StringEntity stringEntity = new StringEntity(jsonObject.toString(), "UTF-8");
        post.setEntity(stringEntity);

        response = client.execute(post);

        if (response != null)
        {
            InputStream in = response.getEntity().getContent();
            status = convertStreamToString(in);// result comes  from server end
        }

    }
    catch (Exception e)
    {
        System.out.println("exception => " + e);
        e.printStackTrace();
    }
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return status;
    }

    @Override
    protected void onPostExecute(String result)
    {
        super.onPostExecute(result);
        try
        {
            System.out.println(result);
        }
        catch (Exception e)
        {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}


public String convertStreamToString(InputStream is) 
    {
        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();
    }

答案 1 :(得分:0)

Use this class 



package com.diluo.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import android.app.ProgressDialog;
import android.content.Entity;
import android.os.AsyncTask;

public class PostCall extends AsyncTask<Void, Void, String>{
    private String url;
    private String request;
    private AsyncTaskListener callListener;
    private int pageId;
    private ProgressDialog dialog;
    public PostCall(String url,String request,ProgressDialog dialog,AsyncTaskListener callListener,int pageId) {
        this.url=url;
        this.request=request;
        this.callListener=callListener;
        this.pageId = pageId;
        this.dialog=dialog;
        }
    @Override
    protected String doInBackground(Void... params) {
        // TODO Auto-generated method stub

            try {

                System.out.println(request);
                System.out.println(url);
                HttpPost post = new HttpPost(this.url);
                StringEntity entity = new StringEntity(request,"UTF-8");
                entity.setContentType("application/json");
                entity.setContentEncoding(new BasicHeader("Content-type","application/json;charset=UTF-8"));
                post.setEntity(entity); 
                post.addHeader("Content-type", "application/json;charset=UTF-80");
                post.setHeader("Accept", "application/json");
                DefaultHttpClient httpClient = new DefaultHttpClient();

                HttpResponse response = httpClient.execute(post); 

                // Collect the response
                HttpEntity entity1=response.getEntity();
                if(entity1 != null&&(response.getStatusLine().getStatusCode()==201||response.getStatusLine().getStatusCode()==200))
                {
                    //--just so that you can view the response, this is optional--
                     int sc = response.getStatusLine().getStatusCode();
                     String sl = response.getStatusLine().getReasonPhrase();
                     String response_string=convertToString(entity1.getContent());
                     return response_string;
                }
                else
                {
                     int sc = response.getStatusLine().getStatusCode();
                     String sl = response.getStatusLine().getReasonPhrase();
                     return null;
                }


            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 

        return null;
    }
    private String convertToString(InputStream content) throws Exception{

            InputStreamReader inputStreamReader=new InputStreamReader(content);
            BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
            String s="";
            StringBuffer buffer=new StringBuffer();
            while ((s=bufferedReader.readLine())!=null) {
                buffer.append(s);
            }

        return buffer.toString();
    }
    @Override
    protected void onPostExecute(String result) {
if( callListener!= null){
    super.onPostExecute(result);
            if(result != null){
                try {
                    System.out.println(result);
                    callListener.onHttpResponse(result, pageId);
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }else{
                callListener.onError("Please try again.", pageId);
            }
            if(this.dialog!=null){
            dialog.dismiss();
            }
            }
        cancel(true);



    }   

}

答案 2 :(得分:0)

尝试以下代码

new AsyncTask<String, Void, String>(){

        @Override
        protected String doInBackground(String... params) {
            HttpClient httpClient = new DefaultHttpClient();
            String url = "your_url";

            HttpPost httppost = new HttpPost(url);
            HttpResponse response;
            try {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);

                nameValuePairs.add(new BasicNameValuePair("action", "action"));
                nameValuePairs.add(new BasicNameValuePair("action2", "action2"));

                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                response = httpClient.execute(httppost);
                HttpEntity entity = response.getEntity();

                if(entity != null){
                    String str = EntityUtils.toString(entity);
                    //do your json here                     
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } 
            return null; 
        }

    }.execute(null,null,null);

答案 3 :(得分:0)

有很多与AsyncTask相关的示例,请仔细阅读AsyncTask