I am trying to use the following method:
public static String UrlToString(String targetURL, List params) {
HttpClient client = new DefaultHttp开发者_如何学JAVAClient();
HttpPost post = new HttpPost(targetURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", "xyz"));
params.add(new BasicNameValuePair("home", "xyz"));
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
InputStream input = response.getEntity().getContent();
//Get the string data from input string and return
...
}
But i want the List<NameValuePair> params = new ArrayList<NameValuePair>();
to be passed with the values added from outside the method. If I remove the three lines from there, I get an error from Eclipse saying there is an uncaught exception. How do I pass the list to the method?
Java is pass by value.
A List reference named params
is passed by value into your method; it's not the same thing as the local variable you create here:
List<NameValuePair> params = new ArrayList<NameValuePair>();
This code cannot possibly have the effect you want.
Your method name should follow the Java coding conventions: it should be urlToString
Finally, if the compiler is telling you that there's an unhandled exception, please add a throws clause to your method signature or add a try/catch block if there's a meaningful handling strategy.
Your signature says the method should return a String, but I don't see a return statement. This won't compile, let alone run.
All those variables that are local to the static method, like the response and input stream, don't appear to do anything. They go out of scope when you exit the method call. As far as I can tell this method is useless as written.
The uncaught exception error is coming from the HttpClient methods. Because they are doing some I/O jobs under the covers, they can throw IOException
in case of I/O failure (e.g. network down, server down, etc) so that you handle such case, for example to take an alternative path or to show an user friendly error message.
You just need to wrap the code in a try-catch
block or to add a throws
declaration. Since you're already using Eclipse, just click the red bullet on the left hand side of the errorneous code line and explore the Eclipse-suggested solutions. If you can handle the exception in a sensible manner, such as returning an alternative response, then choose for the try-catch
and do the handling job inside the catch
. But if you can't handle it in a sensible manner in this particular method, then choose for the throws
clause and let the caller handle it.
See also:
- The Java tutorials - Lesson: Exceptions
精彩评论