apache的HttpClient应用

来源:互联网 发布:电脑usb直连网络 编辑:程序博客网 时间:2024/04/28 23:55

apache的HttpClient是对http客户端的模拟,可以视为代码版的浏览器。android也对HttpClient进行了再次封装(画蛇添足)。

1.HttpURLConnection应用举例

public String sendXML(String path, String xml) throws Exception {StringBuilder sBuilder = new StringBuilder();byte[] data = xml.getBytes();URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("POST");conn.setConnectTimeout(5 * 1000);conn.setDoOutput(true);conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");conn.setRequestProperty("Content-Length", String.valueOf(data.length));OutputStream outStream = conn.getOutputStream();outStream.write(data);outStream.flush();outStream.close();if (conn.getResponseCode() == 200) {BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));String line;while ((line = in.readLine()) != null) {sBuilder.append(line);}}return sBuilder.toString();}

2.java中HttpClient 的应用

try {PostMethod httppost = new PostMethod(path);httppost.setRequestBody(request);int statusCode = httpclient.executeMethod(httppost);if (statusCode == 200) {if (mtype == RESULT_TYPE_OBJECT) {if (line == 0) {oistr = new ObjectInputStream(httppost.getResponseBodyAsStream());result = oistr.readObject();} else {inputStream = httppost.getResponseBodyAsStream();if (inputStream != null) {result = WebRequestI.readStream(inputStream);}}} else {result = httppost.getResponseBodyAsString();}}} catch (Exception e) {e.printStackTrace();} finally {if (oistr != null) {try {oistr.close();oistr = null;} catch (IOException e) {e.printStackTrace();}}}

3.android中HttpClient的应用

public void run() {HttpClient httpclient = new DefaultHttpClient();try {HttpPost httppost = new HttpPost(path);httppost.setEntity(request);HttpResponse response = httpclient.execute(httppost);HttpEntity resEntity = response.getEntity();if (resEntity != null) {if (mtype == RESULT_TYPE_OBJECT) {if (line == 0) {ObjectInputStream res = new ObjectInputStream(resEntity.getContent());result = res.readObject();} else {InputStream inputStream = resEntity.getContent();if (inputStream != null) {result = WebRequestI.readStream(inputStream);}}} else {result = EntityUtils.toString(resEntity);}}if (resEntity != null) {resEntity.consumeContent();}} catch (Exception e) {e.printStackTrace();} finally {try {httpclient.getConnectionManager().shutdown();} catch (Exception ignore) {}}}



0 0
原创粉丝点击