改造:向内部API发出Web请求

时间:2019-03-21 15:14:28

标签: java android

我想向我的组织api发出请求。该请求包含用于会话管理的标头,用户名,密码和Cookie。

下面是我要使用Retrofit重写的实际代码(在HttpClient中)。我听说HttpClient库已被弃用或使用,所以选择了Retrofit。我希望响应包含200个状态代码。

    public static CookieStore cookingStore = new BasicCookieStore();
public static HttpContext context = new BasicHttpContext();
public String getAuth(String login,String password) {
    String resp = null;
    try {
        String url = DOMAIN+"myxyzapi/myanything";
        context.setAttribute(HttpClientContext.COOKIE_STORE, cookingStore);
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        String log = URLEncoder.encode(login, "UTF-8");
        String pass = URLEncoder.encode(password, "UTF-8");
        String json = "username="+log+"&password="+pass+"&maintain=true&finish=Go";
        StringEntity entity = new StringEntity(json);
        post.setEntity(entity); 
        post.addHeader("Content-Type", "application/x-www-form-urlencoded");        
        HttpResponse response = client.execute(post,context);
        resp = EntityUtils.toString(response.getEntity());
        accountPoller();
    } catch(Exception a) {
        log.info("Exception in authentication api:"+a.getMessage().toString());
    }
    return resp;
}

下面是我的代码,我不知道如何通过请求传递上下文HttpResponse response = client.execute(post,**context**);使用改造。 我什至不知道我是否正确提出了改造要求。

try {

        String log = URLEncoder.encode(login, "UTF-8");
        String pass = URLEncoder.encode(password, "UTF-8");

        RequestBody formBody = new FormBody.Builder()
                .add("username=", xyz)
                .add("password=", mypass)
                .add("&maintain=", "true")
                .add("finish=", "Go")
                .build();


        String url = www.xyz.com+"myxyzapi/myanything";

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).post(formBody).addHeader("Content-Type", "application/x-www-form-urlencoded").build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    final String myresp = response.body().string();

                }
            }
        });

    } catch(Exception a) {
        a.getMessage();
    }

1 个答案:

答案 0 :(得分:0)

您必须捕获异常并使用此类。 retrofit2.HttpException

retrofit2 HttpException类

int 码() HTTP状态代码。 串 信息() HTTP状态消息。 响应 响应() 完整的HTTP响应。