改造表单数据POST不返回JSON

时间:2017-03-08 09:06:38

标签: java android json retrofit apache-commons-httpclient

我在使用Apache HttpClient的服务器中尝试此POST并完美运行:

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(BASE_URL + "access.php");
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
            nameValuePairs.add(new BasicNameValuePair(PARAMETER_COD, mAccessCode));
            nameValuePairs.add(new BasicNameValuePair(PARAMETER_USU, mUser));
            nameValuePairs.add(new BasicNameValuePair(PARAMETER_PAS, mPassword));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            try {
                HttpResponse response = httpclient.execute(httppost);
                //JSON RESPONSE
                String op = EntityUtils.toString(response.getEntity(), "UTF-8");

            } catch (IOException e) {
                e.printStackTrace();
            }
            //reset the message text field
        } catch (IOException e) {
            e.printStackTrace();
        }

但我试过让我们改造而不工作:

@Multipart
@POST("access.php")
Call<String> authenticate(@Part("cod") String cod, @Part("usu") String usu, @Part("pas") String pas);

private ApiInterface getInterfaceService(){

    Gson gson = new GsonBuilder()
            .setLenient()
            .create();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

    final ApiInterface mInterfaceService = retrofit.create(ApiInterface.class);
    return mInterfaceService;
}

private void loginProcessWithRetrofit(final User user){

    ApiInterface mApiService = this.getInterfaceService();
    Call<String> mService = mApiService.authenticate(String.valueOf(user.cod),user.pas,user.usu);
    mService.enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {

            //String returnedResponse = mLoginObject.isLogin;
            Toast.makeText(LoginActivity.this, "Returned " + response.body(), Toast.LENGTH_LONG).show();
            showProgress(false);
        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {
            call.cancel();
            Toast.makeText(LoginActivity.this, "Please check your network connection and internet permission", Toast.LENGTH_LONG).show();
            Log.e("Retrofit",t.toString());
        }
    });
}

也可以试试这个帖子:

@POST("access.php")
Call<String> authenticate(@Body User user);

将HttpPost转换为Retrofit的正确形式是什么。 非常感谢。  此致

2 个答案:

答案 0 :(得分:0)

您缺少<? ini_set("log_errors", 1); ini_set("error_log", "err.txt"); ?> <h1>The <code> echo (htmlspecialchars($_POST['test']))</code> is</h1> <hr> <code><? echo htmlspecialchars($_POST['test']); ?></code> <hr> 注释。

@FormUrlEncoded

答案 1 :(得分:0)

使用

Call<JsonElement> mService

**而不是**

Call<String> mService;

在所有地方..添加<String>

的地方