我正在尝试在我的应用程序中使用一个类。直到现在它正在使用HTTPClient类。但是现在HTTpClient类已经弃用了,我需要使用URLConnection类。我想替换下面的代码,但我没有得到如何做到这一点。任何人都可以让我知道。如何做到这一点是我目前的代码:
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost, localContext);
InputStream in = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(in);
如何用HTTPClient类中的URLConnection类替换上面的代码?
答案 0 :(得分:1)
以下是POST的示例:
template <template <typename> class list, typename Type>
void insertion( list<Type>& L )
{
...
}
有关详情,请浏览How to send HTTP request GET/POST in Java。
对于所有已弃用的类,请查看JavaDoc,它将提示用于替换旧代码的类。例如:
private void sendPost() throws Exception {
String url = "your_url";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
因此,我建议使用
...
*
* @deprecated (4.3) use {@link HttpClientBuilder}. <----- THE HINT IS HERE !
*/
@ThreadSafe
@Deprecated
public class DefaultHttpClient extends AbstractHttpClient {
当HttpClientBuilder.create().build();
方法返回build()
-a CloseableHttpClient
时,您可以将声明放在try-with-resources语句中(Java 7 +):
AutoClosable
希望它有所帮助!