public static final String path = "http://121.234.208.67:8080/TestServlet/MainServlet"; public static String postQuest(String name) {
String str = "";
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
conn.setRequestProperty("Content-type",
"application/x-www-form-urlencoded");
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
String content = "post=" + URLEncoder.encode(name, "gb2312");
out.writeBytes(content);
out.flush();
out.close();
BufferedReader br = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
str = br.readLine();
br.close();
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
 上面的是自己写的客户端的向服务器端发送请求的方法
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("gb2312");
String post = request.getParameter("post");
response.setContentType("text/html");
DataOutputStream dos = new DataOutputStream(response.getOutputStream());
//PrintWriter out = response.getWriter();
if (post.equals("first")) {
/*
 * NewsDB ndb = new NewsDB(); List<News> list = ndb.getNews(0, 10);
 * StringBuffer sb = new StringBuffer(); for (int i = 0; i <
 * list.size(); i++) { News n = list.get(i);
 * sb.append(n.getId()+"|"+n.getName()+"#"); }
 */  
String json = "{\"name\":\"reiz\"}";
JSONObject jsonObj = JSONObject.fromObject(json);
String name = jsonObj.getString("name"); jsonObj.put("initial", name.substring(0, 1).toUpperCase()); String[] likes = new String[] { "JavaScript", "Skiing", "Apple Pie" };
jsonObj.put("likes", likes); Map<String, String> ingredients = new HashMap<String, String>();
ingredients.put("苹果", "3kg");     
ingredients.put("糖", "1kg");
ingredients.put("pastry", "2.4kg");
ingredients.put("bestEaten", "outdoors");
jsonObj.put("ingredients", ingredients);
System.out.println(jsonObj.toString());
dos.writeUTF(jsonObj.toString());
} } public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}上面的是服务端servlet代码用writeUTF()方法向客户端返回个json的字符串(测试用的)
客户端也能收到但是在它的前面有一段乱码:À€ï¿½{"ingredients":{"apples":"3kg","pastry":"2.4kg","bestEaten":"outdoors","sugar":"1kg"},"initial":"R","likes":["JavaScript","Skiing","Apple Pie"],"name":"reiz"}多了À€ï¿½乱码。不知道为什么,不知道怎么解决!
哪位大侠看看提供点解决方法。