1

我正在尝试登录服务器以接收 json 文件。但是服务器需要用户名和密码。我不知道如何将它添加到我的构建中。我查看了很多资源,但我无法弄清楚要添加到我的构建器中的内容。非常感谢您的帮助

这是我的 OkhttpHandeler 代码

public class OkHttpHandler extends AsyncTask<String, Void, String> {

OkHttpClient client = new OkHttpClient();
Response response;
Request request;
private final String apUrl = "http://xxxxxxxx.xxxxxx.com/api/1.0/promotions";
String output;
String picture;
//JSon Data
String jsonData;
JSONObject jsonObject;
JSONArray jsonArray;



@Override
protected String doInBackground(String... params) {


    RequestBody formbody = new FormBody.Builder()
            .add("username", "admin")
            .add("password", "admin")
            .build();

    //Request.Builder builder = new Request.Builder();
    //builder.url(params[0]);

    request = new Request.Builder()
            .url(apUrl)
            .post(formbody)
            .build();


    //request = builder.build();

    try {
        response = client.newCall(request).execute();
        Log.d("Respones:", response.body().string());
        output = response.body().string();

        jsonData = output;

        try {
            jsonObject = new JSONObject(jsonData);
            jsonArray = jsonObject.getJSONArray("");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            JSONObject object = jsonArray.getJSONObject(0);

            picture = object.getString("picture");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //return response.body().bytes();
        return picture;

    }catch (Exception e){
        e.printStackTrace();
    }
    return null;
}
}
4

0 回答 0