1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| import java.io.IOException; import java.net.HttpURLConnection; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils;
public class SimpleHttpPoster {
public String doPost(String url) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); CloseableHttpResponse response = httpclient.execute(httpPost); try { if (response != null && response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { return EntityUtils.toString(response.getEntity()); } } catch (IOException e) { e.printStackTrace(); throw e; } finally { response.close(); httpclient.close(); } return null; }
public String doPost(String url, String[] paramNames, String[] paramValues) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); for (int i = 0; i < paramNames.length; i++) { nvps.add(new BasicNameValuePair(paramNames[i], paramValues[i])); } httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8")); CloseableHttpResponse response = httpclient.execute(httpPost); try { if (response != null && response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { return EntityUtils.toString(response.getEntity()); } } catch (IOException e) { e.printStackTrace(); throw e; } finally { response.close(); httpclient.close(); } return null; }
public String doBody(String url, String parmas) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost post = new HttpPost(url); post.addHeader("Content-type", "application/json; charset=utf-8"); post.setHeader("Accept", "application/json"); post.setEntity(new StringEntity(parmas, Charset.forName("utf-8"))); CloseableHttpResponse response = httpclient.execute(post); try { if (response != null && response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { return EntityUtils.toString(response.getEntity()); } } catch (IOException e) { e.printStackTrace(); throw e; } finally { response.close(); httpclient.close(); } return null; }
}
|