2017-03-08 29 views
-7

應用程序向Bringg API發送HTTP請求。我想使用Android中的功能,所以我需要將php代碼轉換爲Java。如何將php-script轉換爲Java?

<? 
$url = 'http://developer-api.bringg.com/partner_api/customers'; 

$data_string = array(
    'access_token' => "<YOUR ACCESS TOKEN>", 
    'timestamp' => date('Y-m-d H:i:s'), 
    'name' => "test c", 
    'company_id' => "<THE COMPANY ID>", 
    'email' => "[email protected]", 
    'allow_sending_sms' => "true" 
); 
$secret_key = "<YOUR SECRET KEY>"; 

// OpenSSL::HMAC.hexdigest("sha1", @partner.hmac_secret, to_query(canonical_params)) 
$signature = hash_hmac("sha1", http_build_query($data_string), $secret_key); 

$data_string["signature"] = $signature; 

$content = json_encode($data_string); 

$ch=curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $content); 
curl_setopt($ch, CURLOPT_HTTPHEADER, 
array('Content-Type:application/json', 
'Content-Length: ' . strlen($content)) 
); 

$json_response = curl_exec($ch); 

$status = curl_getinfo($ch, CURLINFO_HTTP_CODE); 

if ($status != 200) { 
    die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl)); 
} 

curl_close($ch); 

$response = json_decode($json_response, true); 

?> 

我已經使用凌空庫 https://developer.android.com/training/volley/index.html

這樣寫Java代碼,但它總是給我一個空體

String URL = "http://developer-api.bringg.com/partner_api/customers"; 

    String date = Utilitty.getDate(); 
    Log.i(TAG, date); 

    Uri builtUri = Uri.parse("").buildUpon() 
      .appendQueryParameter("access_token", "accesstoken") 
      .appendQueryParameter("timestamp", date) 
      .appendQueryParameter("phone","12889555") 
      .appendQueryParameter("name", "MAhTest") 
      .appendQueryParameter("company_id", "id") 
      .appendQueryParameter("emailz", "[email protected]") 
      .build(); 

    Log.i(TAG, builtUri.toString().substring(1)); 

    HashMap<String, String> param = new HashMap<>(); 
    param.put("access_token", "accesstoken"); 
    param.put("timestamp", date); 
    param.put("phone", "12889555"); 
    param.put("name", "MAhTest"); 
    param.put("company_id", "id"); 
    param.put("email", "[email protected]"); 

    String signature = Utilitty.EncodeToken(builtUri.toString().substring(1), "securtykey"); 
    param.put("signature", signature); 
    Log.i(TAG, signature); 

    JSONObject jsonObject = new JSONObject(param); 
    Log.i(TAG, jsonObject.toString()); 




    JsonObjectRequest req = new JsonObjectRequest(URL, jsonObject, 
      new Response.Listener<JSONObject>() { 
       @Override 
       public void onResponse(JSONObject response) { 
        try { 
         VolleyLog.v("Response:%n %s", response.toString(4)); 
         Log.i(TAG + " Response", response.toString()); 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       } 
      }, 
      new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      VolleyLog.e("Error 1 : ", error.getMessage()); 
     } 
    }); 
    RequestQueue queue = Volley.newRequestQueue(this); 
    queue.add(req); 
+4

歡迎來到Stack Overflow!請查看我們的[SO問題清單](http://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist)來幫助你提出一個好問題,從而得到一個很好的答案。 –

+0

呵呵,@JoeC是絕對正確的。這不是如何工作.. –

回答

0

轉換這個PHP代碼401響應,Java是不是一個好方法。您可以通過背景異步任務線程來解決它。以JSON格式獲取數據,然後解析它以向用戶顯示。例如:

private static String url_all_customers = "http://developer-api.bringg.com/partner_api/customers"; 

    // JSON Node names 
private static final String TAG_SUCCESS = "success"; 
private static final String TAG_CUSTOMERS = "customers"; 
private static final String TAG_CID = "cid"; 
private static final String TAG_NAME = "name"; 
    // products JSONArray 
JSONArray products = null; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.all_customers); 

    // Hashmap for ListView 
    productsList = new ArrayList<HashMap<String, String>>(); 

    // Loading customers in Background Thread 
    new LoadAllCustomers().execute(); 

    // Get listview 
    ListView lv = getListView(); 

    // on seleting single customers 
    // launching Edit Customers Screen 
    lv.setOnItemClickListener(new OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> parent, View view, 
       int position, long id) { 
      // getting values from selected ListItem 
      String pid = ((TextView) view.findViewById(R.id.cid)).getText() 
        .toString(); 

      // Starting new intent 
      Intent in = new Intent(getApplicationContext(), 
        EditProductActivity.class); 
      // sending pid to next activity 
      in.putExtra(TAG_CID, cid); 

      // starting new activity and expecting some response back 
      startActivityForResult(in, 100); 
     } 
    }); 

} 
/** 
* Background Async Task to Load all custormer by making HTTP Request 
* */ 
class LoadAllCustormers extends AsyncTask<String, String, String> { 

    /** 
    * Before starting background thread Show Progress Dialog 
    * */ 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pDialog = new ProgressDialog(AllCustormersActivity.this); 
     pDialog.setMessage("Loading custormers. Please wait..."); 
     pDialog.setIndeterminate(false); 
     pDialog.setCancelable(false); 
     pDialog.show(); 
    } 
protected String doInBackground(String... args) { 
     // Building Parameters 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     // getting JSON string from URL 
     JSONObject json = jParser.makeHttpRequest(url_all_customers, "GET", params); 

     // Check your log cat for JSON reponse 
     Log.d("All Customers: ", json.toString()); 

     try { 
      // Checking for SUCCESS TAG 
      int success = json.getInt(TAG_SUCCESS); 

      if (success == 1) { 
       // products found 
       // Getting Array of Customers 
       customers = json.getJSONArray(TAG_CUSTOMER); 

       // looping through All Customers 
       for (int i = 0; i < customers.length(); i++) { 
        JSONObject c = customers.getJSONObject(i); 

        // Storing each json item in variable 
        String id = c.getString(TAG_CID); 
        String name = c.getString(TAG_NAME); 

        // creating new HashMap 
        HashMap<String, String> map = new HashMap<String, String>(); 

        // adding each child node to HashMap key => value 
        map.put(TAG_PID, id); 
        map.put(TAG_NAME, name); 

        // adding HashList to ArrayList 
        productsList.add(map); 
       } 
      } else { 
       // no customers found 
       // Launch Add New customer Activity 
       Intent i = new Intent(getApplicationContext(), 
         NewCustomerActivity.class); 
       // Closing all previous activities 
       i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
       startActivity(i); 
      } 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    protected void onPostExecute(String file_url) { 
     // dismiss the dialog after getting all customers 
     pDialog.dismiss(); 
     // updating UI from Background Thread 
     runOnUiThread(new Runnable() { 
      public void run() { 
       /** 
       * Updating parsed JSON data into ListView 
       * */ 
       ListAdapter adapter = new SimpleAdapter(
         AllCustomersActivity.this, customersList, 
         R.layout.list_item, new String[] { TAG_CID, 
           TAG_NAME}, 
         new int[] { R.id.cid, R.id.name }); 
       // updating listview 
       setListAdapter(adapter); 
      } 
     }); 

    } 

} 
+0

欲瞭解更多信息使用本教程:http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/ –

+0

所以你的問題是不是關於android的所有!你必須詢問有關php的一部分。請先參閱php手冊:http://php.net/manual/en/function.curl-init.php http://php.net/manual/en/function.curl-setopt.php –