gpt4 book ai didi

java - Android HttpClient 两个不同的 httppost 不起作用?

转载 作者:行者123 更新时间:2023-12-01 11:42:05 25 4
gpt4 key购买 nike

我有以下代码。

  • 我想在用户第一次按下按钮时发布数据将发送到 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)

最佳答案

我希望更有资格的人很快就能回答你的问题,在那之前可能需要研究一下:

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

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

让我觉得如果你不重置 httppost 对象,它就无法重用......

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

关于java - Android HttpClient 两个不同的 httppost 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29444702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com