Java android AsyncHttpClient如何设置标题'接受'一个' application / xml'或者' application / json'

时间:2017-05-10 05:55:31

标签: java android json

我不知道如何设置标题"接受" for' applicatjon / json现在我的服务器响应是一个xml,但我想要一个json。当我设置标题时,服务器应该向我发送一个xml。这是我的代码:

  final JSONObject requestObject = new JSONObject();
        try {
            requestObject.put("company", "TEST");
            requestObject.put("user", "pawelo");
            requestObject.put("secure_password", "8ce241e1ed84937ee48322b170b9b18c");
            requestObject.put("secure_device_id", "C4CA4238A0B923820DCC509A6F75849B");
        } catch (JSONException e) {
            e.printStackTrace();
        }


        StringEntity entity = null;
        try {
            entity = new StringEntity(requestObject.toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
client.post(this, url, entity, "application/json",
            new  BaseJsonHttpResponseHandler("UTF-8") {

                @Override
                public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Object response) {
                    Log.e("sdasa " , rawJsonResponse + " " + statusCode);
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, Object errorResponse) {

                }

                @Override
                protected Object parseResponse(String rawJsonData, boolean isFailure) throws Throwable {
                    return null;
                }
            });

3 个答案:

答案 0 :(得分:1)

            JSONObject json = new JSONObject();

            JSONObject dataJson = new JSONObject();
            dataJson.put("body", message);
            dataJson.put("title", getFirebaseUser().getDisplayName());
            json.put("notification", dataJson);
            json.put("registration_ids",jsonArray);


            StringEntity se = new StringEntity(json.toString(), "UTF-8");

            AsyncHttpClient client = new AsyncHttpClient();
            client.addHeader("Accept", "application/json");
            client.addHeader("Content-type", "application/json;charset=utf-8");
            client.addHeader("Authorization", "key=" + "xxxxxxxxxxxx");
            client.post(getInstance(), "your url", se, "application/json;charset=utf-8", new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    Log.e("success_noti", new String(responseBody) + "");

                    if(isEnd){
                        getMessage.getMessageFunc(END);
                    }

                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    Log.e("fail_noti", new String(responseBody) + "");
                }
            });

使用AsyncHttpClient库这也是另一种方法。

答案 1 :(得分:0)

当您向服务器发送请求时,可以在标题上添加接受行。

        URL url;
        HttpURLConnection urlConnection = null;
        String response = null;
        InputStream in = null;
        try {
            url = new URL(urlStr);
       urlConnection = (HttpURLConnection) url.openConnection();
            /* optional request header */
            urlConnection.setRequestProperty("Content-Type", "application/json");

                /* optional request header */
            urlConnection.setRequestProperty("Accept", "application/json");

            urlConnection.setRequestMethod("GET");


            //InputStream in = urlConnection.getInputStream();


            int statusCode = urlConnection.getResponseCode();

                /* 200 represents HTTP OK */

            if (statusCode == 200) {
                in = new BufferedInputStream(urlConnection.getInputStream());
                response = Utils.convertInputStreamToString(in);

           } 


        } catch (Exception e) {
           e.printStackTrace();

        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }

答案 2 :(得分:0)

使用此代码

   public String POST(String url, Been been){
    InputStream inputStream = null;
    String result = "";
    try {
        HttpPost httpPost = new HttpPost(url);

        String json = "";
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("company", Been.getcompany());
        jsonObject.accumulate("user",  Been.getuser());
        jsonObject.accumulate("secure_password",  Been.getpassword());
       jsonObject.accumulate("secure_device_id", Been.getdevice_id());

        json = jsonObject.toString();

        StringEntity se = new StringEntity(json);

        httpPost.setEntity(se);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        HttpResponse httpResponse1 = httpclient.execute(httpPost);
        inputStream = httpResponse1.getEntity() .getContent();

        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {

        Log.d("InputStream", e.getLocalizedMessage());
    }


    return result;
}

使用AsyncTask调用方法

  public class HttpAsyncTask extends AsyncTask<Void, Void, String> {
    private ProgressDialog mProgressDialog;
    private DefaultHttpClient httpclient;
    private HttpPost httppost;
    @Override
    protected String doInBackground(Void... params) {
        httpclient = new DefaultHttpClient();

        //Create new HTTP POST with URL to php file as parameter
        httppost = new HttpPost(url);

        Been = new Been();
        Been.setcompany("TEST");
        Been.setuser("pawelo");
        Been.setpassword("8ce241e1ed84937ee48322b170b9b18c");
        Been.setdevice_id("C4CA4238A0B923820DCC509A6F75849B");


        return POST(url, Been);
    }

    @Override
    protected void onPostExecute(String result) {

        mProgressDialog.dismiss();
    }

    @Override
    protected void onPreExecute() {

        mProgressDialog = ProgressDialog.show(getActivity(), "", "loading...");
        mProgressDialog.setCancelable(false);
        mProgressDialog.setCanceledOnTouchOutside(false);
    }

}

创建Boon类

 public class Been {

private String name;
private String user;
private String password;
private String device_id;


public String getcompany() {
    return name;

}

public void setcompany(String name1) {
    this.name= name1;
}

public String getuser() {
    return user;

}

public void setuser(String user1) {
    this.user= user1;
}
public String getpassword() {
    return user;

}

public void setpassword(String password1) {
    this.password= password1;
}
public String getdevice_id() {
    return user;

}

public void setdevice_id(String device_id1) {
    this.device_id= device_id1;
}
}