【问题标题】:Not getting json response from server in android没有从android中的服务器获得json响应
【发布时间】:2015-07-24 11:54:00
【问题描述】:

我已经编写了从服务器获取 json 数据的代码..但是它在输入流中给出了异常。请建议我正确的答案.... 当我运行代码时,它一直运行到 httpresponse 并且当我看到日志时..它显示消息“只有主线程可以触摸视图”

   package com.example.http;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.ComponentName;

public class MainActivity extends Activity {

    static EditText etResponse;
    TextView tvIsConnected;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // get reference to the views
        etResponse = (EditText) findViewById(R.id.etResponse);
        tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);



        // show response on the EditText etResponse 
        //etResponse.setText(GET("http://hmkcode.com/examples/index.php"));

        // call AsynTask to perform network operation on separate thread
        new HttpAsyncTask().execute("http://api.frankly.me/search/default");
    }




    public static String GET(String url){
        InputStream inputStream = null;
        String result = "";
        try {

            // create HttpClient
            HttpClient httpClient = new DefaultHttpClient();

            // make GET request to the given URL
            //HttpResponse httpResponse = httpclient.execute(new HttpGet(url));

            HttpPost httpPost = new HttpPost("http://api.frankly.me/search/default");
            HttpResponse httpResponse = null;

            try {

                httpResponse = httpClient.execute(httpPost);

                if(httpResponse.getStatusLine().getStatusCode()==200)
                    etResponse.setText("got");
                etResponse.setText(httpResponse.toString());
                // writing response to log
                Log.d("Http Response:", httpResponse.toString());

            } catch (ClientProtocolException e) {
                // writing exception to log
                e.printStackTrace();

            } catch (IOException e) {
                // writing exception to log
                e.printStackTrace();
            }

            // receive response as inputStream
           inputStream = httpResponse.getEntity().getContent();

            // convert inputstream to string
            if(inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";

        } catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }

        return result;
    }

    private static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }

    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {


            return GET(urls[0]);
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            runOnUiThread(new Runnable() {
             @Override
             public void run() {

        //stuff that updates ui
                Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();     
            }
        });


       }
    }

}

【问题讨论】:

    标签: android multithreading asynchronous task


    【解决方案1】:
    etResponse.setText("got");
    

    您正试图在后台线程的EditText 上设置文本。从doInBackground 返回结果并将EditText 上的文本设置在onPostExecute

    此外,onPostExecute 中不需要 runOnUiThread,因为 onPostExecute 在 UI 线程上运行。

    【讨论】:

    【解决方案2】:

    我建议将 Volley.jar 用于 Web 服务 here is the demo.它的响应速度非常快且易于实施。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 2017-03-19
      • 1970-01-01
      • 1970-01-01
      • 2019-09-11
      • 1970-01-01
      相关资源
      最近更新 更多