如何将php脚本转换为Java?

如何将php脚本转换为Java?,java,php,android,http,android-studio,Java,Php,Android,Http,Android Studio,应用程序向Bringg API发送HTTP请求。我想在Android中使用该功能,所以我需要将php代码翻译成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'), 'n

应用程序向Bringg API发送HTTP请求。我想在Android中使用该功能,所以我需要将php代码翻译成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' => "abctest@test.com",
  '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);

?>

我已经使用volley库编写了这段Java代码

但它总是给我一个401的回应,而我的身体是空的

    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", "mody5060@gmail.com")
            .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", "mody5060@gmail.com");

    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);
stringurl=”http://developer-api.bringg.com/partner_api/customers";
字符串日期=Utilitty.getDate();
日志i(标签、日期);
Uri builtUri=Uri.parse(“”.buildon()
.appendQueryParameter(“访问令牌”、“访问令牌”)
.appendQueryParameter(“时间戳”,日期)
.appendQueryParameter(“电话”,“12889555”)
.appendQueryParameter(“名称”、“测试”)
.appendQueryParameter(“公司id”、“id”)
.appendQueryParameter(“emailz”)mody5060@gmail.com")
.build();
Log.i(标记,builduri.toString().substring(1));
HashMap param=新的HashMap();
参数put(“访问令牌”、“访问令牌”);
参数put(“时间戳”,日期);
参数put(“电话”、“12889555”);
参数put(“名称”、“测试”);
参数put(“公司id”、“id”);
参数put(“电子邮件”)mody5060@gmail.com");
字符串签名=Utilitty.EncodeToken(builtUri.toString().substring(1),“securtykey”);
参数put(“签名”,签名);
日志i(标签、签名);
JSONObject JSONObject=新的JSONObject(参数);
i(标记,jsonObject.toString());
JsonObjectRequest req=新的JsonObjectRequest(URL,jsonObject,
新的Response.Listener(){
@凌驾
公共void onResponse(JSONObject响应){
试一试{
VolleyLog.v(“响应:%n%s”,响应.toString(4));
Log.i(标记+“Response”,Response.toString());
}捕获(JSONException e){
e、 printStackTrace();
}
}
},
新的Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
e(“错误1:,错误.getMessage());
}
});
RequestQueue=Volley.newRequestQueue(this);
队列添加(req);

将此PHP代码转换为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);
            }
        });

    }

}
私有静态字符串url\u所有客户=”http://developer-api.bringg.com/partner_api/customers";
//JSON节点名称
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
私有静态最终字符串标记_CUSTOMERS=“CUSTOMERS”;
私有静态最终字符串标记_CID=“CID”;
私有静态最终字符串标记_NAME=“NAME”;
//产品JSONArray
JSONArray产品=null;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.all_客户);
//ListView的Hashmap
productsList=新的ArrayList();
//在后台线程中加载客户
新建LoadAllCustomers().execute();
//获取列表视图
ListView lv=getListView();
//论单一客户的选择
//启动“编辑客户”屏幕
lv.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父级、视图、,
内部位置,长id){
//从选定的ListItem获取值
字符串pid=((TextView)view.findViewById(R.id.cid)).getText()
.toString();
//开始新的意图
Intent in=新的Intent(getApplicationContext(),
EditProductActivity.class);
//将pid发送到下一个活动
in.putExtra(标记CID,CID);
//开始新的活动并期望得到一些响应
startActivityForResult(in,100);
}
});
}
/**
*通过发出HTTP请求加载所有客户机的后台异步任务
* */
类LoadAllCustomers扩展了AsyncTask{
/**
*在启动后台线程显示进度对话框之前
* */
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=newprogressdialog(allcustomersactivity.this);
pDialog.setMessage(“正在加载客户机。请稍候…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(假);
pDialog.show();
}
受保护的字符串doInBackground(字符串…args){
//建筑参数
List params=new ArrayList();
//从URL获取JSON字符串
JSONObject json=jParser.makeHttpRequest(url_all_customers,“GET”,params);
//检查日志cat中的JSON响应
Log.d(“所有客户:,json.toString());
试一试{
//检查成功标签
int success=json.getInt(TAG_success);
如果(成功==1){
//发现的产品
//获取大量客户
customers=json.getJSONArray(TAG_CUSTOMER);
//在所有客户中循环
对于(int i=0;ivalue
地图放置(标签PID,id);
地图放置(标签名称、名称);
//将哈希列表添加到ArrayList
productsList.add(地图);
}
}否则{
//没有找到客户
//启动添加新客户活动
意图i=新意图(getApplicationContext(),
纽卡斯特