1 package com.foxinmy.weixin4j.server.test;
2
3 import java.io.IOException;
4 import java.net.URI;
5
6 import org.apache.http.Consts;
7 import org.apache.http.HttpResponse;
8 import org.apache.http.HttpStatus;
9 import org.apache.http.StatusLine;
10 import org.apache.http.client.HttpClient;
11 import org.apache.http.client.methods.HttpGet;
12 import org.apache.http.client.methods.HttpPost;
13 import org.apache.http.entity.StringEntity;
14 import org.apache.http.impl.client.DefaultHttpClient;
15 import org.apache.http.util.EntityUtils;
16
17 import com.foxinmy.weixin4j.util.ServerToolkits;
18
19
20
21
22
23
24
25
26
27
28 public class MessagePush {
29
30 private final String server = "http://localhost:30000";
31 private final HttpClient httpClient;
32 private final HttpPost httpPost;
33 private final HttpGet httpGet;
34
35 public MessagePush() {
36 httpClient = new DefaultHttpClient();
37 httpPost = new HttpPost();
38 httpPost.setURI(URI.create(server));
39
40 httpGet = new HttpGet();
41 httpGet.setURI(URI.create(server));
42 }
43
44 public String get(String para) throws IOException {
45 httpGet.setURI(URI.create(server + para));
46 HttpResponse httpResponse = httpClient.execute(httpGet);
47 return entity(httpResponse);
48 }
49
50 public String push(String xml) throws IOException {
51 return push("", xml);
52 }
53
54 public String push(String para, String xml) throws IOException {
55 httpPost.setURI(URI.create(server + para));
56 httpPost.setEntity(new StringEntity(xml, Consts.UTF_8));
57 HttpResponse httpResponse = httpClient.execute(httpPost);
58 return entity(httpResponse);
59 }
60
61 private String entity(HttpResponse httpResponse) throws IOException {
62 StatusLine statusLine = httpResponse.getStatusLine();
63
64 int status = statusLine.getStatusCode();
65 if (status != HttpStatus.SC_OK) {
66 throw new IOException(Integer.toString(status) + "request fail");
67 }
68 if (status == HttpStatus.SC_MOVED_PERMANENTLY
69 || status == HttpStatus.SC_MOVED_TEMPORARILY) {
70 throw new IOException(Integer.toString(status) + "uri moved");
71 }
72 return EntityUtils.toString(httpResponse.getEntity(),
73 ServerToolkits.UTF_8);
74 }
75 }