apache post 连接网络 读取返回数据

本文详细介绍了Android应用如何通过HTTP POST方法发起网络请求,包括创建HttpClient、设置参数、发送请求以及处理响应数据的过程。重点阐述了如何从服务器获取JSON格式数据并将其解析为可读格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

下面是post的:

public class Test extends Activity implements OnClickListener {

    public Context context;

 

    private TextView textView1;

 

    public static String URL ="http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";

 

    private DefaultHttpClient httpClient;

 

    private static final int TIMEOUT = 60;

 

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        init();

        try {

 

 

            HttpParams paramsw = createHttpParams();

            httpClient = new DefaultHttpClient(paramsw);

            /* 建立HTTP Post连线 */

            HttpPost post = new HttpPost("http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl");

 

 

//            URI uri = new URI(URL);

//            HttpPost post = new HttpPost();

//            post.setURI(uri);

 

 

            // Post运作传送变数必须用NameValuePair[]阵列储存

            List<NameValuePair> params = new ArrayList<NameValuePair>();

            params.add(new BasicNameValuePair("name", "this is post"));

//            params.add(new BasicNameValuePair("version", getVersionCode(context) + ""));

//            params.add(new BasicNameValuePair("os", "android"));

//            params.add(new BasicNameValuePair("flag", "10"));

//            params.add(new BasicNameValuePair("modle", getModelNumber()));

//            params.add(new BasicNameValuePair("channel", "samsung"));

 

 

 

            try {

 

                // 发出HTTP request,把字符集设置在request里面

                post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

                 //相当于打开链接,给出回应

                HttpResponse httpResponse = httpClient.execute(post);

 

                int httpCode = httpResponse.getStatusLine().getStatusCode();

 

 

                //HTTP_OK=200,服务器作出反映,找到了服务器,并且回应了。

                if (httpCode == HttpURLConnection.HTTP_OK) {

 

//                  //取出回应字串

//                    String strResult=EntityUtils.toString(httpResponse.getEntity());

//                    textView1.setText(strResult);

 

                   //这里可以做很多事 

                    Header[] headers=httpResponse.getAllHeaders();

                    HttpEntity entity=httpResponse.getEntity();

                    Header header=httpResponse.getFirstHeader("content-type");

 

                    //下面是从流中把字符串读出来了

                    InputStream inputStream=entity.getContent();

                    InputStreamReader inputStreamReader=new InputStreamReader(inputStream);

                    BufferedReader reader = new BufferedReader(inputStreamReader);//读字符串用的。

                    String inputLine = null;

                    String result = "";

                    // 使用循环来读取获得的数据,把数据都村到result中了

                    while (((inputLine = reader.readLine()) != null)) {

                        // 我们在每一行后面加上一个"\n"来换行

                        result += inputLine + "\n";

                    }

                    reader.close();//关闭输入流

 

 

 

 

                }else {

                    textView1.setText("Error Response"+httpResponse.getStatusLine().toString());

                }

 

 

 

 

            } catch (UnsupportedEncodingException e) {

                textView1.setText("网络连接错误UnsupportedEncodingException");

            } catch (ClientProtocolException e) {

                textView1.setText("网络连接错误ClientProtocolException");

            } catch (IOException e) {

                textView1.setText("网络连接错误IOException");

            }

        } finally {

 

            if (httpClient != null) {

                httpClient.getConnectionManager().shutdown();//最后关掉链接。

                httpClient = null;

            }

        }

    }

    /**

     * 手机型号

     * 

     * @return

     */

    private String getModelNumber() {

        String modelNo = "Unknown";

        try {

            modelNo = Build.MODEL;

        } catch (Exception e) {

            // ignored

        }

        return modelNo;

    }

 

    /**

     * 获得版本CODE

     * 

     * @param context

     * @return

     */

    public static int getVersionCode(Context context) {

        PackageManager pm = context.getPackageManager();

        try {

            PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);

            if (info != null) {

                return info.versionCode;

            }

        } catch (NameNotFoundException e) {

            e.printStackTrace();

        }

 

        return 1;

    }

 

    /**

     * Create the default HTTP protocol parameters.

     */

    public static final HttpParams createHttpParams() {

        final HttpParams params = new BasicHttpParams();

        // Turn off stale checking. Our connections break all the time anyway,

        // and it's not worth it to pay the penalty of checking every time.

        HttpConnectionParams.setStaleCheckingEnabled(params, false);

        //设置链接超时,socket超时,以及socket大小。

        HttpConnectionParams.setConnectionTimeout(params, TIMEOUT * 1000);

        HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000);

        HttpConnectionParams.setSocketBufferSize(params, 8192 * 5);

        return params;

    }

    private void init() {

        // TODO Auto-generated method stub

        textView1 = (TextView) findViewById(R.id.txt);

        Button button1 = (Button) findViewById(R.id.button1);

        Button button2 = (Button) findViewById(R.id.button2);

        Button button3 = (Button) findViewById(R.id.button3);

        button1.setOnClickListener(this);

        button2.setOnClickListener(this);

        button3.setOnClickListener(this);

    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值