【问题标题】:Converting a JSON response to string using a webservice in android使用 android 中的 web 服务将 JSON 响应转换为字符串
【发布时间】:2014-07-07 12:47:14
【问题描述】:

我正在使用网络服务来检索 JSON 并将其转换为字符串。但我将字符串设为空。

MainActivity 类是:

package com.example.webserviceeg;

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 java.util.Date;
import java.util.List;
import java.util.TimeZone;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    Button btnshowdata;
    TextView txtdata;
    String URL="http://www.footballultimate.com/fifa/index.php/api/matchShedule/";
   ProgressBar pb;
   HttpResponse response;
   String result;
   HttpEntity entity;
   InputStream is;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnshowdata=(Button) findViewById(R.id.btnshowdata);
        txtdata=(TextView) findViewById(R.id.txtdata);
        pb=(ProgressBar) findViewById(R.id.progressBar1);
        btnshowdata.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                new Retrievevalues().execute();

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
public class Retrievevalues extends AsyncTask<String,Void,Void>
{
    @Override
    protected void onPreExecute() {


        pb.setVisibility(View.VISIBLE);





    }

    @Override
    protected Void doInBackground(String... params) {
        try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(URL);
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
//      TimeZone tz = TimeZone.getDefault();
//      Date now = new Date();
//      int offsetFromUtc = tz.getOffset(now.getTime()) / 1000;
        pairs.add(new BasicNameValuePair("time_offset","19800"));

            httppost.setEntity(new UrlEncodedFormEntity(pairs));



             response = httpclient.execute(httppost);

          result=responsetostring.getResponseBody(response);
          Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
         // txtdata.setText(result);
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;


    }

    @Override
    protected void onPostExecute(Void result) {



        pb.setVisibility(View.INVISIBLE);
    }

}
}

我正在使用包含静态方法的第二个类将响应对象转换为字符串:

responsetostring.java

 package com.example.webserviceeg;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.protocol.HTTP;

public class responsetostring {
    // Json Response Processing
     // Json Response Processing
    public static String getResponseBody(HttpResponse response) {
        // TODO Auto-generated method stub
        String response_text = null;

        HttpEntity entity = null;

        try {
            entity = response.getEntity();
            try {
                response_text = _getResponseBody(entity);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response_text;

    }
    public static String _getResponseBody(final HttpEntity entity) throws IOException,
        ParseException {

    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }

    InputStream instream = entity.getContent();
    if (instream == null) {
        return "";
    }

    if (entity.getContentLength() > Integer.MAX_VALUE) {
        throw new IllegalArgumentException(
                "HTTP entity too large to be buffered in memory");
    }

    String charset = getContentCharSet(entity);

    if (charset == null) {
        charset = HTTP.DEFAULT_CONTENT_CHARSET;
    }

    Reader reader = new InputStreamReader(instream, charset);

    StringBuilder buffer = new StringBuilder();

    try {

        char[] tmp = new char[1024];

        int l;

        while ((l = reader.read(tmp)) != -1) {

            buffer.append(tmp, 0, l);

        }

    } finally {

        reader.close();

    }

    return buffer.toString();

}
    public static String getContentCharSet(final HttpEntity entity)
            throws ParseException {

        if (entity == null) {
            throw new IllegalArgumentException("HTTP entity may not be null");
        }

        String charset = null;

        if (entity.getContentType() != null) {
            HeaderElement values[] = entity.getContentType().getElements();

            if (values.length > 0) {
                NameValuePair param = values[0].getParameterByName("charset");

                if (param != null) {
                    charset = param.getValue();
                }
            }
        }

        return charset;
    }

}

但是字符串导致 MainActivity ,我得到它为空。请帮助

【问题讨论】:

  • 你从哪里得到null
  • 请检查您的 logcat ..我认为您在某些地方被抛出异常
  • 我在 LOGCAT:07-07 07:44:02.633: W/System.err(2056): java.lang.RuntimeException: Can't create handler inside the thread that has not称为 Looper.prepare()
  • 现在可以在 do 背景中使用 toast,所以我调用了一个单独的方法

标签: java android json web-services


【解决方案1】:

改成这样:

if (instream != null) {
BufferedReader reader = new BufferedReader(
                new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();

        return sb.toString();

}
else
{
return "";
}

【讨论】:

  • 不行,即使改了代码,主activity中result变量依然为null。
  • 你确定有一些回应吗?
  • 我调试了代码并检查了它,响应对象有一个值。
  • 响应对象不为空。字符串结果为空。请帮忙!
  • 还有一件事.. Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();永远不会在 doInBackground 方法中工作
猜你喜欢
  • 2016-07-01
  • 2018-04-06
  • 2018-05-08
  • 1970-01-01
  • 2016-12-09
  • 2012-10-14
  • 2012-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多