开发者

Multiple Difficulties with HttpURLConnection class in Java for Android

开发者 https://www.devze.com 2023-03-20 12:50 出处:网络
--Update-- Apologies for those who helped me, it turns out this is just a problem with开发者_运维百科 Eclipse\'s debugger. After suspecting that it was leading me wrong, I placed down a couple of Syst

--Update--

Apologies for those who helped me, it turns out this is just a problem with开发者_运维百科 Eclipse's debugger. After suspecting that it was leading me wrong, I placed down a couple of System.out.println to watch the variables, and according to them they ARE being changed, and that the debugger was just showing me old information for whatever reason. No clue why that's happening, but the important thing is that the code does apparently actually work.

I'm working on a method to share with twitter for an Android application, and I'm having errors when setting up the HttpURLConnection. I create the connection object as per usual, using the openconnection function of a url then casting it to a HttpURLConnection, and when I subsequently run SetRequestMethod("POST") on the connection, it does absolutely nothing. When I run the code in the debugger line by line, as I go through that line the request method just remains as the default ("GET"). Anyone have any idea as to why this may be happening? I'm getting the same problem with setDoOutput(true) also not changing anything. However, adding a request property does still work. I've been searching around and haven't been able to find anything on this problem, not even another person reporting these problems.


I am not sur whether using HttpURLConnection is the best here.

Did you try the following way?

// Building the POST request
final BasicNameValuePair message   = new BasicNameValuePair("yourField", "yourContent");
final List<NameValuePair> list     = new ArrayList<NameValuePair>(1);

list.add(message);

final HttpPost httppost = createHttpPost(UrlEncodedFormEntity(list));

// Building the HTTP client
final HttpParams httpParameters = new BasicHttpParams();

HttpConnectionParams.setConnectionTimeout(httpParameters, YOUR_CHOSEN_CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout        (httpParameters, YOUR_CHOSEN_SO_TIMEOUT);

final HttpClient httpClient = new DefaultHttpClient(httpParameters);

// Execution of the POST request
final HttpResponse response = httpClient.execute(httppost);

This is the way I usually do, with no problems.

[EDIT: 04-25-2014] Apache's HttpClient was the best approach for Froyo and former versions. Now, according to this article from Android Developers Blog (written after this Q&A), it is better to use URLConnection.

0

精彩评论

暂无评论...
验证码 换一张
取 消