使用POST和GET中的AsyncTask HTTP请求(Using both POST and G

2019-10-21 02:51发布

我在开发应用的过程中得到的数据从服务器

步骤1:使用发布HTTP POST与特定的报头的内容URL的请求。

第2步:作为回报,我会得到一个链接,我已经构建成一个完整的URL的一部分

STRP 3:现在,通过使用HTTP GET方法来获取数据这个URL。

我现在想实现这个使用下面的代码,

@Override
    protected String doInBackground(String... params) 
    {
        try 
        {
            /** Performing POST method to url to obtain link for data**/
            HttpClient httpClient = HttpClientConstant.getThreadSafeClient();
            HttpPost httpPost = new HttpPost(CHANNEL_LANGUAGE_SENTIMENT_URL);
            httpPost.setEntity(new ByteArrayEntity(POST_URL_VALUES.toString().getBytes("UTF8")));
            HttpResponse response = httpClient.execute(httpPost);
            if(response!=null)
            {
                OBTAIN_URL_LINK = convertJsonToString(response.getEntity().getContent()).toString();
                /** getting the link in OBTAIN_URL_LINK**/
                System.out.println("Response: " + OBTAIN_URL_LINK);
                try
                {
                    /** Constructing the URL**/
                    JSONObject mainStringJSON = new JSONObject(OBTAIN_URL_LINK);
                    REFINED_URL_LINK = mainStringJSON.getString("poll_url");
                    REQUIRED_URL_LINK = PREDEFINED_URL_LINK + REFINED_URL_LINK;
                    System.out.println("URL to USE: " + REQUIRED_URL_LINK);

                    /** Performing GET method to obtain the Data**/
                    HttpClient channelHttpClient = HttpClientConstant.getThreadSafeClient();
                    HttpGet channelHttpGet = new HttpGet(REQUIRED_URL_LINK);
                    HttpResponse channelHttpResponse = channelHttpClient.execute(channelHttpGet);

                    /** Reading the JSON response and stroing in string**/
                    BufferedReader channelHttpReader = new BufferedReader(new InputStreamReader(channelHttpResponse.getEntity().getContent(), "UTF-8") );
                    CHANNEL_LANGUAGE_RESPONSE_JSON = channelHttpReader.readLine();
                    System.out.println(CHANNEL_LANGUAGE_RESPONSE_JSON);
                    if(CHANNEL_LANGUAGE_RESPONSE_JSON != null)
                    {   
                        try
                        {       
                            JSONObject mainJson = new JSONObject(CHANNEL_LANGUAGE_RESPONSE_JSON);
                            JSONObject dataJson = mainJson.getJSONObject("data");
                            //JSONObject dataJson = new JSONObject().getJSONObject("data");
                            /** Values for Channel Graphs**/
                            JSONObject channelJson = dataJson.getJSONObject("category");
                            int twitterValues = channelJson.getInt("twitter");

当我debugg的应用程序,它做工精细,它显示的数据。 但是当我运行它的崩溃,并给我这个应用程序,

10-07 09:03:10.517: I/System.out(1330): org.json.JSONException: No value for data
10-07 09:03:10.517: I/System.out(1330):     at org.json.JSONObject.get(JSONObject.java:354)
10-07 09:03:10.517: I/System.out(1330):     at org.json.JSONObject.getJSONObject(JSONObject.java:569)
10-07 09:03:10.557: I/System.out(1330):     at m_brain.m_adaptive.m_DetailActivity.ChannelsAndLanguageFilterFragment$GetChannelAndLanguageData.doInBackground(ChannelsAndLanguageFilterFragment.java:164)
10-07 09:03:10.597: I/System.out(1330):     at m_brain.m_adaptive.m_DetailActivity.ChannelsAndLanguageFilterFragment$GetChannelAndLanguageData.doInBackground(ChannelsAndLanguageFilterFragment.java:1)
10-07 09:03:10.597: I/System.out(1330):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-07 09:03:10.637: I/System.out(1330):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
10-07 09:03:10.637: I/System.out(1330):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
10-07 09:03:10.637: I/System.out(1330):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-07 09:03:10.669: I/System.out(1330):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
10-07 09:03:10.708: I/System.out(1330):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
10-07 09:03:10.747: I/System.out(1330):     at java.lang.Thread.run(Thread.java:856)
10-07 09:03:10.917: I/Choreographer(1330): Skipped 35 frames!  The application may be doing too much work on its main thread.
10-07 09:03:11.047: D/AndroidRuntime(1330): Shutting down VM
10-07 09:03:11.047: W/dalvikvm(1330): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
10-07 09:03:11.077: E/AndroidRuntime(1330): FATAL EXCEPTION: main
10-07 09:03:11.077: E/AndroidRuntime(1330): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
10-07 09:03:11.077: E/AndroidRuntime(1330):     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
10-07 09:03:11.077: E/AndroidRuntime(1330):     at java.util.ArrayList.get(ArrayList.java:304)
10-07 09:03:11.077: E/AndroidRuntime(1330):     at m_brain.m_adaptive.m_DetailActivity.ChannelsAndLanguageFilterFragment.generatePieDataChannels(ChannelsAndLanguageFilterFragment.java:311)
10-07 09:03:11.077: E/AndroidRuntime(1330):     at m_brain.m_adaptive.m_DetailActivity.ChannelsAndLanguageFilterFragment.access$11(ChannelsAndLanguageFilterFragment.java:304)
10-07 09:03:11.077: E/AndroidRuntime(1330):     at m_brain.m_adaptive.m_DetailActivity.ChannelsAndLanguageFilterFragment$GetChannelAndLanguageData.onPostExecute(ChannelsAndLanguageFilterFragment.java:270)
10-07 09:03:11.077: E/AndroidRuntime(1330):     at m_brain.m_adaptive.m_DetailActivity.ChannelsAndLanguageFilterFragment$GetChannelAndLanguageData.onPostExecute(ChannelsAndLanguageFilterFragment.java:1)
10-07 09:03:11.077: E/AndroidRuntime(1330):     at android.os.AsyncTask.finish(AsyncTask.java:631)
10-07 09:03:11.077: E/AndroidRuntime(1330):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
10-07 09:03:11.077: E/AndroidRuntime(1330):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
10-07 09:03:11.077: E/AndroidRuntime(1330):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-07 09:03:11.077: E/AndroidRuntime(1330):     at android.os.Looper.loop(Looper.java:137)
10-07 09:03:11.077: E/AndroidRuntime(1330):     at android.app.ActivityThread.main(ActivityThread.java:4745)
10-07 09:03:11.077: E/AndroidRuntime(1330):     at java.lang.reflect.Method.invokeNative(Native Method)
10-07 09:03:11.077: E/AndroidRuntime(1330):     at java.lang.reflect.Method.invoke(Method.java:511)
10-07 09:03:11.077: E/AndroidRuntime(1330):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-07 09:03:11.077: E/AndroidRuntime(1330):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-07 09:03:11.077: E/AndroidRuntime(1330):     at dalvik.system.NativeStart.main(Native Method)

我在一个片段这样做的,在图形这是在一个ListView中显示的数据。 我是初学者在这一点,所以请指导我,如果我在一个错误的方式做这件事还是需要不同的方法。 而且我不能够理解,如果这是因为HTTP请求或其他任何hapening。 该生产线是显示在try方法的终点。

Answer 1:

你可以使用这个类此处理:

import java.io.IOException;
import java.io.UnsupportedEncodingException;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class ServiceHandler 
{

    private JSONObject response = null;

    public final static int GET = 1;

    public final static int POST = 2;

    public JSONObject makeServiceCall( String url, int method )
    {

        return this.makeServiceCall( url, method, null );

    }

    public JSONObject makeServiceCall( String url, int method, List<NameValuePair> params )
    {

        try
        {

            DefaultHttpClient httpClient = new DefaultHttpClient();

            HttpEntity httpEntity = null;

            HttpResponse httpResponse = null;

            if( method == POST )
            {

                HttpPost httpPost = new HttpPost( url );

                if( params != null )
                {

                    httpPost.setEntity( new UrlEncodedFormEntity( params, "UTF-8" ) );

                }

                httpResponse = httpClient.execute( httpPost );

            }else if( method == GET )
            {

                if( params != null )
                {

                    String paramString = URLEncodedUtils.format( params, "UTF-8" );

                    url += "?" + paramString;

                }

                HttpGet httpGet = new HttpGet( url );

                //Envia a URL e pega a resposta.
                httpResponse = httpClient.execute( httpGet );

            }

            httpClient = null;

            httpEntity = httpResponse.getEntity();

            httpResponse = null;

            String JSONString = EntityUtils.toString( httpEntity );

            Log.e( "JSON", JSONString );

            try
            {

                response = new JSONObject( JSONString );

            }catch( JSONException e ) { }

            httpEntity = null;

        }catch( UnsupportedEncodingException e ) 
        {

            e.printStackTrace();

        }catch( ClientProtocolException e ) 
        {

            e.printStackTrace();

        }catch( IOException e )
        {

            e.printStackTrace();

        }

        return response;

    }

}

如何使用:

ServiceHandler serviceHandler = new ServiceHandler();

JSONObject jsonObj = serviceHandler.makeServiceCall( URL, ServiceHandler.POST OR ServiceHandler.GET, PARAMS );


Answer 2:

http://developer.android.com/reference/org/json/JSONObject.html#getJSONObject(java.lang.String)

抛出JSONException如果映射不存在或不是一个JSONObject。

JSONObject dataJson = mainJson.getJSONObject("data");

这种失败,因为相关联的“数据”的对象不存在。

使用有方法,以确保它的存在

if (mainJson.has("data"))
{
    JSONObject dataJson = mainJson.getJSONObject("data");
    JSONObject channelJson = dataJson.getJSONObject("category");
    // [...]
}


文章来源: Using both POST and GET http request in AsyncTask