【问题标题】:Android HttpClient Two different httpposts not working?Android HttpClient 两个不同的 httpposts 不起作用?
【发布时间】:2015-04-04 09:17:51
【问题描述】:

我有以下代码。

  • 我想在用户第一次按下按钮时发布数据将发送到 httpclient 并返回数据。这很好用(按钮 1)。当用户按下按钮 1 时,它会给出正确的结果。
  • 然后我想第二次将不同的数据发布到 httpclient。当用户按下按钮 2 时。数据将被发送到函数,但日志(见代码)每次 NULL 时都会在异常中返回。所以我认为它不会发送到httpclient,也不会用我要发送的数据填充httppost。

我的问题是,我做错了什么或忘记了什么?

  • 是否需要创建第二个 httpclient 处理程序?
  • 是否需要创建第二个 httppost 处理程序?

请帮忙。

谢谢。

import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.Random;

    import info.androidhive.customlistviewvolley.util.MyHttpClient;

    public class Login extends Activity  {
      

        HttpPost httppost;
        HttpResponse response;
        HttpClient httpclient;
        List<NameValuePair> nameValuePairs;
        ProgressDialog dialog = null;
        ProgressDialog offlineDialog = null;
        String logged, token, valid;
        String expired = "expired";
        String status, responseContent = "0";
        String msg = "";

        public void onCreate(Bundle savedInstanceState) {
        
          httpclient=new MyHttpClient(getApplicationContext());
          httppost= new HttpPost("https://www.test.com/json/index.php");
          
          b = (Button)findViewById(R.id.buttonLogin);
          c = (Button)findViewById(R.id.shareData);
          
          b.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog = ProgressDialog.show(Login.this, "","Validating user...", true);
                    new Thread(new Runnable() {
                        public void run() {
                            login();
                        }
                    }).start();
                }
            });

           String username = 'abc';
           String password = 'xxx';
           String token = '12321abcksadkm';

c.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    offlineDialog = ProgressDialog.show(Login.this, "", "Share content...", true);
                    new Thread(new Runnable() {
                        public void run() {
                            // This will be executed but will give NULL and offcourse no results
                            share.connectDP(username,password,"share","18228",token);
                        }
                    }).start();
                }
            });
          
        }
        
        void login(){
        try{

            final byte[] SALT;

            Random random = new Random();
            random.setSeed(System.currentTimeMillis());
            byte[] buf = new byte[20];
            random.nextBytes(buf);
            SALT = buf;

            nameValuePairs = new ArrayList<NameValuePair>(3);
            nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim()));
            nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
            nameValuePairs.add(new BasicNameValuePair("token",SALT.toString().trim()));

            Log.i("Salt", "Key =" + SALT.toString().trim());
            Log.i("test", "test" + nameValuePairs);

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            //Execute HTTP Post Request
            response=httpclient.execute(httppost);

            String responseContent = EntityUtils.toString(response.getEntity());
            //Log.d("Response", responseContent );

            JSONObject jsonObject = new JSONObject(responseContent);
            JSONArray jArray = jsonObject.getJSONArray("result");

            for (int i = 0; i < jArray.length(); i++) {
                try {
                    JSONObject json_data = jArray.getJSONObject(i);
                    logged = json_data.getString("status"); // obtain status
                    token = json_data.getString("token"); // obtain token
                    valid = json_data.getString("valid"); // obtain validation period
                    expired = "no";
                    Log.i("Logged JSON", "Result?" + json_data.getString("status"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
         }catch(Exception e){
            dialog.dismiss();
            System.out.println("Exception : " + e.getMessage());
        }
      }

      public void connectDP(String username, String password, String action, String id, String token){

        // This is passed, it returns the data = :)
        Log.i("connect", "username" + username);
        Log.i("connect", "password" + password);
        Log.i("connect", "action" + action);
        Log.i("connect", "id" + id);
        Log.i("connect", "token" + token);

        try{

            final byte[] SALT;

            Random random = new Random();
            random.setSeed(System.currentTimeMillis());
            byte[] buf = new byte[20];
            random.nextBytes(buf);
            SALT = buf;

            nameValuePairs = new ArrayList<NameValuePair>(3);
            nameValuePairs.add(new BasicNameValuePair("username",username.toString().trim()));
            nameValuePairs.add(new BasicNameValuePair("password",password.toString().trim()));
            nameValuePairs.add(new BasicNameValuePair("token",SALT.toString().trim()));

            Log.i("Salt", "Key =" + SALT.toString().trim());
            Log.i("test", "test" + nameValuePairs);

            //// <!---- After here it will break, but no any error or warning -----!>

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            //Execute HTTP Post Request
            response=httpclient.execute(httppost);

            String responseContent = EntityUtils.toString(response.getEntity());
            //Log.d("Response", responseContent );

            JSONObject jsonObject = new JSONObject(responseContent);
            JSONArray jArray = jsonObject.getJSONArray("result");

            for (int i = 0; i < jArray.length(); i++) {
                try {
                    JSONObject json_data = jArray.getJSONObject(i);
                    logged = json_data.getString("status"); // obtain status
                    token = json_data.getString("token"); // obtain token
                    valid = json_data.getString("valid"); // obtain validation period
                    expired = "no";
                    Log.i("Logged JSON", "Result?" + json_data.getString("status"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
         }catch(Exception e){
            dialog.dismiss();
            System.out.println("Exception : " + e.getMessage());
        }

    }

      
    }

04-03 19:33:22.380  12220-12220/info.androidhive.customlistviewvolley I/connect﹕ usernameabc
04-03 19:33:22.380  12220-12220/info.androidhive.customlistviewvolley I/connect﹕ passwordxxx
04-03 19:33:22.380  12220-12220/info.androidhive.customlistviewvolley I/connect﹕ actionshare
04-03 19:33:22.380  12220-12220/info.androidhive.customlistviewvolley I/connect﹕ id18228
04-03 19:33:22.380  12220-12220/info.androidhive.customlistviewvolley I/connect﹕ token12321abcksadkm
04-03 19:33:22.380  12220-12220/info.androidhive.customlistviewvolley I/test 1﹕ test[username=abc, password=xxx, requestAction=share, requestFile=18228, load_remote_token=12321abcksadkm
04-03 19:33:22.380  12220-12220/info.androidhive.customlistviewvolley D/test 1a﹕ testnull
04-03 19:33:22.380  12220-12220/info.androidhive.customlistviewvolley D/test 2﹕ testnull
04-03 19:33:22.380  12220-12220/info.androidhive.customlistviewvolley D/test 2a﹕ testnull
04-03 19:33:22.380  12220-12220/info.androidhive.customlistviewvolley D/test 3﹕ testnull
04-03 19:33:22.380  12220-12220/info.androidhive.customlistviewvolley D/test 4﹕ testnull
04-03 19:33:22.380  12220-12220/info.androidhive.customlistviewvolley D/test 4a﹕ testnull
04-03 19:33:22.380  12220-12220/info.androidhive.customlistviewvolley D/test 5﹕ 0
04-03 19:33:22.380  12220-12220/info.androidhive.customlistviewvolley I/System.out﹕ Exception : Value 0 of type java.lang.Integer cannot be converted to JSONObject
04-03 19:33:22.380  12220-12220/info.androidhive.customlistviewvolley I/Log share﹕ [ 04-03 19:33:25.390   169:0x204 W/InputManagerService ]
    Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@4156a2c8

package info.androidhive.customlistviewvolley.util;
import android.content.Context;
import info.androidhive.customlistviewvolley.R;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import java.io.InputStream;
import java.security.KeyStore;
import org.apache.http.conn.ssl.SSLSocketFactory;

public class MyHttpClient extends DefaultHttpClient {

    final Context _context;

    public MyHttpClient(Context context) {
        this._context = context;
    }

    @Override
    protected ClientConnectionManager createClientConnectionManager() {
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        // Register for port 443 our SSLSocketFactory with our keystore
        // to the ConnectionManager
        registry.register(new Scheme("https", (org.apache.http.conn.scheme.SocketFactory) newSslSocketFactory(), 443));
        return new SingleClientConnManager(getParams(), registry);
    }

    private SSLSocketFactory newSslSocketFactory() {
        try {
            // Get an instance of the Bouncy Castle KeyStore format
            KeyStore trusted = KeyStore.getInstance("BKS");
            // Get the raw resource, which contains the keystore with
            // your trusted certificates (root and any intermediate certs)
            InputStream in = _context.getResources().openRawResource(R.raw.keystore);
            try {
                // Initialize the keystore with the provided trusted certificates
                // Also provide the password of the keystore
                trusted.load(in, "xxxxxxxx".toCharArray());
            } finally {
                in.close();
            }
            // Pass the keystore to the SSLSocketFactory. The factory is responsible
            // for the verification of the server certificate.
            SSLSocketFactory sf = new SSLSocketFactory(trusted);
            // Hostname verification from certificate
            // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
            sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            return sf;
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }
}

04-04 22:39:06.890  15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ java.lang.NullPointerException
04-04 22:39:06.890  15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at info.androidhive.customlistviewvolley.Login.connectDP(Login.java:247)
04-04 22:39:06.890  15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at info.androidhive.customlistviewvolley.adater.CustomGridOfflineMedia$2.onClick(CustomGridOfflineMedia.java:200)
04-04 22:39:06.890  15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.view.View.performClick(View.java:3511)
04-04 22:39:06.890  15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.view.View$PerformClick.run(View.java:14110)
04-04 22:39:06.890  15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:605)
04-04 22:39:06.890  15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:92)
04-04 22:39:06.890  15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
04-04 22:39:06.890  15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:4424)
04-04 22:39:06.890  15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
04-04 22:39:06.890  15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
04-04 22:39:06.890  15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-04 22:39:06.890  15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-04 22:39:06.890  15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)

【问题讨论】:

  • 请张贴logcat
  • 我已经发布了 logcat。感谢您的帮助。

标签: java android http-post httpclient


【解决方案1】:

我希望有更合格的人能尽快回答你的问题,在此之前可能需要调查一下:

HttpPost.reset 继承自 AbstractExecutionAwareRequest 在文档中说:

“重置请求的内部状态,使其可重用。”

让我觉得,如果你不重置 httppost 对象,它可能是不可重用的......

源代码:http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/methods/AbstractExecutionAwareRequest.html#reset()

【讨论】:

  • 链接将来可能会改变,所以如果你能在这里简要定义一下这个概念会更好。
【解决方案2】:

根据 logcat,您的 API 没有响应有效的 JSON 格式。

它必须是 "response" : "0" 或类似的东西,而不是普通的 0。

我建议你检查connectDB函数的服务器端代码以及它返回的内容。

【讨论】:

  • 谢谢,但是第一个调用 login() 的 onclicklistener (b); = 工作。如果我用相同的函数替换第二个 onclicklistener (c) 所以我用 login() 中的代码替换 connectDP 中的所有内容,它仍然不会给出任何结果。服务器端脚本工作正常。我认为这与双 httppost 或关闭 httppost 并开始第二个 httppost 有关。
  • 第一个可能有效,但第二个 API 出现错误,您验证了吗?使用 rest-client 或 poster 等工具验证您的回复
  • 响应 = {"result":[{"status":1,"message":"共享请求成功。","token":"$6$rounds=5000$usesomeDPStringf$o90sKrB. l9gXiPeYzvVc60bggWqt9yoW2Jbj1LpyeRGW5.BE4eu8ylFsXs6nqvCTgCGock8P7GJxew7XDXA9s\/","valid":"1432918351","file":"{\"success\":true}"}]}
  • 也许它打破了这个,“文件”:“{\”成功\“:真}”}]}。我认为该响应是有效的,但可能不适用于android。我将尝试使用 isJSONValid() 来解决这个问题。当我实现这个时,我会发布一条消息。
  • 有效。但即使我做了两次相同的请求(请参阅编辑后的代码),它也不会发布。
【解决方案3】:

这已通过更改一些代码解决。

【讨论】:

  • 请将更新后的代码作为答案,并接受。它将在未来的案例中帮助其他人。
  • 我将第二个 httppost 移至另一个视图。我没有找到在 1 个视图中执行两次 httppost 的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-05
相关资源
最近更新 更多