需要帮助将HttpClient转换为HttpURLConnection

时间:2016-08-10 16:23:59

标签: java android post httpurlconnection

我需要一些帮助才能将HttpClient转换为HttpURLConnection。我在网上关注这个教程,它真的很老了。如果有更新更好的方法来编写一些代码,请告诉我。

本教程将向您展示如何使用Android在Drupal上发布文章。休息时间

提前致谢。

public String session_id;
public String session_name;

//click listener for addArticle button
public void saveArticleButton_click(View view){
    //initiate the background process to post the article to the Drupal endpoint.
    //pass session_name and session_id
    new addArticleTask().execute(session_name, session_id);
}

//asynchronous task to add the article into Drupal
private class addArticleTask extends AsyncTask<String, Void, Integer> {

    protected Integer doInBackground(String... params) {
        //read session_name and session_id from passed parameters
        String session_name=params[0];
        String session_id=params[1];

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://app.flickgo.com/apistuff/node.json");

        try {
            //get title and body UI elements
            TextView txtTitle = (TextView) findViewById(R.id.editTextTitle);
            TextView txtBody = (TextView) findViewById(R.id.editTextBox);

            //extract text from UI elements and remove extra spaces
            String title = txtTitle.getText().toString().trim();
            String body = txtBody.getText().toString().trim();

            //add raw json to be sent along with the HTTP POST request
            StringEntity se = new StringEntity( " { \"title\":\""+title+"\",\"type\":\"article\",\"body\":{\"und\":[{ \"value\":\""+body+"\"}]}}");
            se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            httppost.setEntity(se);

            BasicHttpContext mHttpContext = new BasicHttpContext();
            CookieStore mCookieStore = new BasicCookieStore();

            //create the session cookie
            BasicClientCookie cookie = new BasicClientCookie(session_name, session_id);
            cookie.setVersion(0);
            cookie.setDomain("app.flickgo.com");
            cookie.setPath("/");
            mCookieStore.addCookie(cookie);
            cookie = new BasicClientCookie("has_js", "1");
            mCookieStore.addCookie(cookie);
            mHttpContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore);

            httpclient.execute(httppost,mHttpContext);

            return 0;

        }catch (Exception e) {
            Log.v("Error adding article",e.getMessage());
        }
        return 0;
    }

    protected void onPostExecute(Integer result) {
        //start the List Activity and pass back the session_id and session_name
        Intent intent = new Intent(AddArticle.this, ListActivity.class);
        intent.putExtra("SESSION_ID", session_id);
        intent.putExtra("SESSION_NAME", session_name);
        startActivity(intent);

        //stop the current activity
        finish();
    }
}
}

1 个答案:

答案 0 :(得分:1)

HttpURLConnection有一个笨拙的API。您可以尝试使用OK HTTP。无论如何,我认为HttpURLConnection代码如下:

CookieManager cookies = new CookieManager();
cookies.getCookieStore().add(null, new HttpCookie("app.flickgo.com", "/"));
cookies.getCookieStore().add(null, new HttpCookie("has_js", "1"));
cookies.getCookieStore().add(null, new HttpCookie(session_name, session_id));

URL url = new URL("http://app.flickgo.com/apistuff/node.json");
HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
urlconnection.setRequestMethod("POST");
urlconnection.setDoOutput(true);
urlconnection.setRequestProperty("Content-Type", "application/json");

try(OutputStreamWriter writer = new OutputStreamWriter(urlconnection.getOutputStream())) {
    writer.write("{\"title\":\""+title+"\",\"type\":\"article\",\"body\":{\"und\":[{ \"value\":\""+body+"\"}]}}");
}

int rc = urlconnection.getResponseCode();