所以,我使用的是 Android Studio 1.2.1.1、oKhttp 2.5.0、okio 1.6.0,我已经正确设置了依赖项(我相信),而且我到处找,所以我必须做一些非常简单的错误,因为没有其他人似乎对此有问题。
我有一个名为 OkHttpPostHandler 的 Java 类,代码如下
import android.os.AsyncTask;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import java.io.IOException;
public class OkHttpPostHandler extends AsyncTask<String, Void, String> {
OkHttpClient client = new OkHttpClient();
String varUser, varPass;
public OkHttpPostHandler(String varUser, String varPass) {
this.varUser = varUser;
this.varPass = varPass;
}
@Override
protected String doInBackground(String... params){
RequestBody formBody = new FormEncodingBuilder()
.add("u", varUser)
.add("p", varPass)
.build();
Request request = new Request.Builder()
.url(params[0]).post(formBody)
.build();
try {
android.util.Log.w("Test", formBody.toString());
Response response = client.newCall(request).execute();
if (!response.isSuccessful())
throw new IOException("unexpected code " + response.toString());
return response.body().string();
} catch (Exception e) {
}
return null;
}
}
我有一个按钮,它读取两个 EditText 视图以获取用户名和密码,然后触发 http 调用:
@Override
public void onClick(View bnLoginSubmit) {
EditText loginUsernameFont = (EditText) findViewById(R.id.evUsername);
EditText loginPasswordFont = (EditText) findViewById(R.id.evPassword);
String varUsername = loginUsernameFont.getEditableText().toString();
String varPassword = loginPasswordFont.getEditableText().toString();
String varPasswordHash = BCrypt.hashpw(varPassword, BCrypt.gensalt());
if (varUsername.isEmpty() || varPassword.isEmpty() || varUsername.contentEquals("") || varPassword.contentEquals("")) {
Toast.makeText(getApplicationContext(), "Username and/or Password Cannot be Empty",
Toast.LENGTH_LONG).show();
} else {
// sendPostRequest(varUsername, varPasswordHash);
boolean varPassCheck = BCrypt.checkpw("Password", varPasswordHash);
OkHttpPostHandler handler = new OkHttpPostHandler("Username_String","Password_String");
String result = null;
try {
result = handler.execute("http://www.example.com").get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "PHP Response = " + result,
Toast.LENGTH_LONG).show();
}
}
我认为问题出在我的 bcrypt 散列(所以我使用手动输入的字符串进行测试),但这似乎工作得很好。只是我的参数没有被传递。如果我将参数手动输入到 URL 中,它会正确返回,但我希望能够在此类上进行构建,以便将来调用时它可以是动态的。
谁能看到我做错了什么?它必须是简单的。任何帮助将不胜感激,因为我正在努力确定问题。