我正在构建应用程序,它将发送用户名并通过POST作为JSONObject传递给我的php脚本,该脚本读取params,获取一些信息,然后将它们作为JSON发送回我的应用程序。
我用Postman在我的机器上测试了脚本,它返回了预期的结果。
但是当我在app中调用它时,urlConnection返回代码响应-1,在完成writer部分后。 这是代码:
MainActivity extends AppCompatActivity implements AsyncResponse
- getJson(View view)
此方法由点击
public void getJson(View view) {
String user = ((EditText) findViewById(R.id.username)).getText().toString();
String pass = ((EditText) findViewById(R.id.passwordTxtField)).getText().toString();
Toast t;
if (user.isEmpty() || pass.isEmpty()) {
t = Toast.makeText(this, "Polja ne mogu biti prazna!", Toast.LENGTH_LONG);
t.show();
return;
}
t = Toast.makeText(this, "Prosledjeni parametri:\nUser: " + user + " Pass: " + pass, Toast.LENGTH_LONG);
t.show();
JSONObject json = new JSONObject();
try {
json.put("user_name", user);
json.put("password", pass);
} catch (JSONException e) {
e.printStackTrace();
}
if (json.length() > 0) {
sendParams(user, pass);
}
}
private void sendParams(String user, String pass) {
JSONObject json = new JSONObject();
try {
json.put("user_name", user);
json.put("password", pass);
} catch (JSONException e) {
e.printStackTrace();
}
if (json.length() > 0) {
SendAuthParams sap = (SendAuthParams) new SendAuthParams().execute(String.valueOf(json));
//call to async class
}
}
public void processFinish(String s) {
((TextView) findViewById(R.id.textView)).setText(s);
}
致电SendAuthParams extends AsyncTask<String, String, String>
public AsyncResponse delegate = null;
private static final String TAG = "SEND";
private String result;
private HttpURLConnection urlConnection;
protected String doInBackground(String... params) {
String JsonResponseString = null;
String JsonDATAString = params[0];
HttpURLConnection urlConnection = null;
BufferedReader br = null;
try { //had to change port because...Skype
URL url = new URL("http://myIPv4:81/path/index.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
// urlConnection
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.connect();
//Write
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(JsonDATAString);
writer.flush();
writer.close();
os.close();
//Read
StringBuilder sb = null;
//here is the problem
int responseCode=urlConnection.getResponseCode();
if(responseCode==HttpURLConnection.HTTP_OK){
String line;
sb = new StringBuilder();
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is,"UTF-8");
br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
JsonResponseString = sb.toString();
Log.i(TAG, JsonResponseString);
//send to post execute
return JsonResponseString;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (br != null) {
try {
br.close();
} catch (final IOException e) {
Log.e(TAG, "Error closing stream", e);
}
}
}
return "jbga";
}
@Override
protected void onPostExecute(String s) {
delegate.processFinish(s);
}}
仅用于从postExecute发送结果 -
public interface AsyncResponse {
void processFinish(String s);
}
而index.php - 正常工作:
<?php
$json = file_get_contents('php://input');
$userPass = json_decode($json,true);
$url = 'http://someUrl';
// Open a curl session for making the call
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
// Tell curl not to return headers, but do return the response
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the POST arguments
$parameters = array(
'user_auth' => array(
'user_name' =>$userPass['user_name'],
'password' => md5($userPass['password']),
),
);
$json = json_encode($parameters);
$postArgs = array(
'method' => 'login',
'input_type' => 'JSON',
'response_type' => 'JSON',
'rest_data' => $json,
);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($curl);
// Convert the result from JSON format to a PHP array
$result = json_decode($response);
if ( !is_object($result) ) {
die("Error handling result.\n");
}
if ( !isset($result->id) ) {
die("Error: {$result->name} - {$result->description}\n.");
}
// If login success then u get your session id to do task
$session = $result->id;
// Get record
$fields_array = array('first_name','last_name','phone_mobile','phone_work');
$parameters = array(
'session' => $session, //Session ID
'module_name' => 'Contacts', //Module name
'query' => "", //Where condition without "where" keyword
'order_by' => " leads.last_name ", //$order_by
'offset' => 0, //offset
'select_fields' => $fields_array, //select_fields
'link_name_to_fields_array' => array(array()), //optional
'max_results' => 5, //max results
'deleted' => 'false', //deleted
);
$json = json_encode($parameters);
$postArgs = array(
'method' => 'get_entry_list',
'input_type' => 'JSON',
'response_type' => 'JSON',
'rest_data' => $json,
);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
$response = curl_exec($curl);
/* Output header */
header('Content-type: application/json');
echo $response;
?>
几乎要忘记,关于错误,它只会抛出NullPointer,告诉null传递给onPostExecute。按道理。希望你们能帮忙。