Retrofit_2 http POST return 403 message

0 人关注

我正在尝试将Java源代码转换为Android。这是一个执行http POST然后接收json数据的Java代码。而且效果很好。

public String httpPost(){
String url = "https://webapi.com/api?" 
  List<NameValuePair> params; 
  List<NameValuePair> headers;
  params.add(new BasicNameValuePair("command", commandValue));
  params.add(new BasicNameValuePair("nonce", 
  String.valueOf(System.currentTimeMillis())));
  headers.add(new BasicNameValuePair("Key", API_KEY));
  headers.add(new BasicNameValuePair("Sign", SECRET_SIGNATURE);
  HttpPost post = new HttpPost(url);
        post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
        String str = post.getEntity().toString();
        if (headers != null)
            for (NameValuePair header : headers)
                post.addHeader(header.getName(), header.getValue());
        HttpResponse response = httpClient.execute(post);
        HttpEntity entity = response.getEntity();
        if (entity != null)
           return  EntityUtils.toString(entity);
    return null;

这是使用Retrofit 2的Android源代码。
APIServiceInterface.java

 @POST("api")
    Call<Mymodel> httpPost(@Header("Key") String key,
                                                 @Header("Sign") String sign,
                                                 @Query("command") String command,
                                                 @Query("nonce") String nonce);

APIClient.java

public class ApiClient {
    private static Retrofit retrofit = null;
    public static Retrofit getClient(String baseUrl) {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        return retrofit;

POST request

    String url = "https://webapi.com/";
    APIServiceInterface apiService =   ApiClient.getClient(url).create(APIServiceInterface.class);
    Call<MyModel> call = apiService.httpPost(apiKey, secretSignature, commandValue,  String.valueOf(System.currentTimeMillis()));
            call.enqueue(new Callback<MyModel>() {
                @Override
                public void onResponse(Call<MyModel> call, Response<MyModel> response) {
                    int statusCode = response.code();
                        Log.d(TAG,"http  POST:\n[header]:\n" + call.request().headers() +
                    "\n[request]:\n" + call.request().toString() +
                    "\n[body]: \n" + call.request().body().toString()+
                    "\n----------------------------------------------"+
                    "\nResponse:\n[header]:\n" + response.headers() +
                    "\n[body]:\n"+ response.body() +
                    "\n[raw]:" + response.raw() +
                    "\n[status] :" + response.code() +
                    "\n[message] :" + response.message());
                @Override
                public void onFailure(Call<MyModel> call, Throwable t) {
                    // Log error here since request failed
                    Log.e(TAG, "Request failed :" + t.toString());

This is debug log

http  POST:
[header]:
Key: MHKVXY9C-9WE8N6CS-L1ETB10V-TFUA4S8G
Sign: 2534CCB0C58850B4FA621539D5AA5ACB0433B8F47070E6ED13757006F85FF1E4244D3118BDE107C46A7F5587C06BA201F74DE10003330ECBD352757D23E57ACA
[request]:
Request{method=POST, url=https://webapi.com/api?command=commandValue&nonce=nonceValue, tag=null}
[body]: 
okhttp3.RequestBody$2@1751ef1
----------------------------------------------
Response:
[header]:
date: Tue, 05 Dec 2017 07:07:50 GMT
content-type: text/html; charset=UTF-8
set-cookie: __cfduid=d0c467a5dbc10a660a569227616baa28f1512457670; expires=Wed, 05-Dec-18 07:07:50 GMT; path=/; domain=.webapi.com; HttpOnly
cf-chl-bypass: 1
cache-control: max-age=2
expires: Tue, 05 Dec 2017 07:07:52 GMT
x-frame-options: SAMEORIGIN
server: cloudflare-nginx
cf-ray: 3c852bb78ea732ef-HKG
[body]:
[raw]:Response{protocol=h2, code=403, message=, url=https://webapi.com/api?command=commandValue&nonce=nonceValue}
[status] :403
[message] :

然而,安卓的源代码并不工作,它总是返回403消息。 我的代码是不是哪里错了?
谁能帮助我!?谢谢。

2 个评论
用logcat提供完整的错误
neo
我更新了我的问题和调试日志,请看一下。我认为帖子的标题出了问题,也许有什么东西丢失了,但我还没有弄清楚。
android
http-post
retrofit2
androidhttpclient
neo
neo
发布于 2017-12-05
3 个回答
Aks4125
Aks4125
发布于 2020-09-16
已采纳
0 人赞同

Verify Key & Sign headers from server first.

403 Forbidden错误是一个HTTP状态代码,意味着由于某种原因,访问你试图到达的页面或资源是绝对禁止的。

核实你所传递的头信息和内容类型,然后在下面测试 邮递员 see if works.

如果你的api在postman中不工作,那么你在Android中就没有办法使它工作。

尝试与http客户端一起传递头信息。

httpClient.addInterceptor(chain -> {
        Request original = chain.request();
        // Request customization: add request headers
        Request.Builder requestBuilder = original.newBuilder()
                .header("Key", API_KEY)
                .header("Sign", SECRET_SIGNATURE);
                .header("Content-Type", "application/json"); // set your content type
        Request request = requestBuilder.build();
        return chain.proceed(request);
    Retrofit retrofit = builder.client(httpClient.build()).build();
  

岗位API应该是

 @POST("api")
Call<Mymodel> httpPost(
                       @Query("command") String command,
                       @Query("nonce") String nonce);
    
user3880554
user3880554
发布于 2020-09-16
0 人赞同

我认为你的证书可能是正确的,但你从 CloudFlare 服务器(cloudflare-nginx)而不是从你的服务器(webapi)获得错误 403。 你的请求需要通过cloudflare来实现。

shubomb
shubomb
发布于 2020-09-16
0 人赞同