码迷,mamicode.com
首页 > Web开发 > 详细

HttpClient 的使用

时间:2016-06-24 20:39:55      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:httpclient

                     HttpClient 的简单使用

服务端的代码:

 

package com.paic.test.web.httpServer;

 

import java.io.IOException;

import java.io.PrintWriter;

 

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

/**

 * Servlet implementation classHelloServlet

 */

@WebServlet("/HelloServlet")

public class HelloServlet extends HttpServlet {

    private static final longserialVersionUID= 1L;

   public HelloServlet() {

        super();

   }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {

        //response.setCharacterEncoding("UTF-8");

        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out=response.getWriter();

        String jsonStr="{‘deviceid‘:‘SH01H20130002‘,‘productid‘:‘SH01H20130007‘}";

        //输出数据

        out.write(jsonStr);

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {

        this.doGet(request,response);

    }

 

 

客户端的代码:

package com.paic.test.web.httpClients;

 

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.util.EntityUtils;

import org.json.JSONObject;

/**

 * httpClient 客户端获取数据

*/

public class HelloClient {

    public static void main(String[] args) {

        HttpClient hc=new DefaultHttpClient();

        String serversUrl="http://10.65.4.3:8080/test-servers/HelloServlet";

        HttpPost hp=new HttpPost(serversUrl);

        StringresultStr="";

        try {

            hp.addHeader("Content-type","application/x-www-form-urlencoded");     

            HttpResponse response =hc.execute(hp); 

            if (response.getStatusLine().getStatusCode() ==200) {

              resultStr=EntityUtils.toString(response.getEntity());

              JSONObject js=new JSONObject(resultStr);

              System.out.println(js.get("deviceid"));

              System.out.println(js.get("productid"));

//                System.out.println(js.getString("deviceid"));

            }else{

              System.out.println("获取数据失败!");

            }

        }catch(Exception e) {

            System.out.println("获取数据失败了,错误原因:"+e.getMessage());

        }finally{

           

        }

    }  

}


本文出自 “10964919” 博客,请务必保留此出处http://10974919.blog.51cto.com/10964919/1792674

HttpClient 的使用

标签:httpclient

原文地址:http://10974919.blog.51cto.com/10964919/1792674

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!